cefsharp入坑实践3

 

关于浏览器拦截的问题,解决方案是加入自定义的资源处理器,代码如下:

//设置自定义的资源处理器工厂
// browser.ResourceHandlerFactory = new MyResourceHandlerFactory();
var request = new MyRequestHandler();
(browser as IWebBrowser).RequestHandler = new MyRequestHandler();

 

/// <summary>
/// 自定义请求处理器(涉及到敏感信息的,用internal类型)
/// </summary>
internal class MyRequestHandler : CefSharp.Handler.DefaultRequestHandler
{

public override IResponseFilter GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
{
if (request.Url.StartsWith("file") && request.Url.EndsWith(".png") && request.Url.IndexOf("/png/") > 0)
{
string keyfile= request.Url.Substring(0, request.Url.Length - 4) + ".key";
keyfile = keyfile.Substring(8);
if (File.Exists(keyfile))
//此处判断当需要对response进行额外处理时,返回一个Filter实例。(判断语法仅供参考)
return new MyResponseFilter();
else
return base.GetResourceResponseFilter(browserControl, browser, frame, request, response);
}
else
return base.GetResourceResponseFilter(browserControl, browser, frame, request, response);
}

}


/// <summary>
/// 自定义响应过滤器(涉及到敏感信息的,用internal类型)
/// </summary>
internal class MyResponseFilter : IResponseFilter
{
int _filterindex = 0;
public MyResponseFilter()
{

}

public void Dispose()
{
}

/// <summary>
/// 获取输入流,经过处理后,写到输出流
/// </summary>
/// <param name="dataIn">输入流</param>
/// <param name="dataInRead">从输入流中读取的数量</param>
/// <param name="dataOut">输出流</param>
/// <param name="dataOutWritten">写入输出流的数量</param>
/// <returns></returns>
public FilterStatus Filter(Stream dataIn, out long dataInRead, Stream dataOut, out long dataOutWritten)
{
//注意,除本函数内,其它任何位置不得引用dataIn,dataOut
if (dataIn == null)
{
dataInRead = 0;
dataOutWritten = 0;

return FilterStatus.Done;
}

//若有更复杂的加密方式,处理方式应该类似

dataIn.CopyTo(dataOut);
dataInRead = dataIn.Length;
dataOutWritten = Math.Min(dataInRead, dataOut.Length);
_filterindex++;
return FilterStatus.NeedMoreData;
}

public bool InitFilter()
{
return true;
}
}

上一篇:WebKit应用程序开发的起因


下一篇:当javascript尝试解析包含从C#发送的列表的对象时,CefSharp崩溃