CefSharp资源拦截及自定义处理代码
时间: 2023-12-07 10:03:13 浏览: 198
在CefSharp中,可以通过实现`IRequestHandler`接口来实现资源拦截及自定义处理。以下是一个示例代码:
```csharp
public class CustomRequestHandler : IRequestHandler
{
public bool OnBeforeBrowse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isRedirect)
{
return false;
}
public bool OnBeforeResourceLoad(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
{
// 判断资源类型
if (request.ResourceType == ResourceType.Image)
{
// 拦截图片资源
callback.Cancel();
return true;
}
return false;
}
public void OnResourceResponse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
{
}
public bool GetAuthCredentials(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
{
return false;
}
public bool OnCertificateError(IWebBrowser chromiumWebBrowser, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
{
return false;
}
public void OnPluginCrashed(IWebBrowser chromiumWebBrowser, IBrowser browser, string pluginPath)
{
}
public bool OnRenderProcessTerminated(IWebBrowser chromiumWebBrowser, IBrowser browser, CefTerminationStatus status)
{
return false;
}
public bool OnResourceRedirect(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, ref string newUrl)
{
return false;
}
public bool OnQuotaRequest(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, long newSize, IRequestCallback callback)
{
return false;
}
public void OnRenderViewReady(IWebBrowser chromiumWebBrowser, IBrowser browser)
{
}
public void OnResourceLoadComplete(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
{
}
public bool OnProtocolExecution(IWebBrowser chromiumWebBrowser, IBrowser browser, string url)
{
return false;
}
public void OnRenderProcessThreadCreated(IWebBrowser chromiumWebBrowser, IBrowser browser, IRenderProcessHost renderProcessHost)
{
}
public bool OnResourceResponseFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, IResponseFilter filter)
{
return false;
}
public void OnResourceLoadError(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, CefErrorCode errorCode, string errorText, IRequestCallback callback)
{
}
}
```
在上述代码中,我们主要实现了`OnBeforeResourceLoad`方法,用于拦截资源请求并进行处理。在本示例中,我们拦截了所有类型为图片的资源,并取消其加载,实现了资源拦截的功能。
要应用这个自定义请求处理程序,可以通过以下方式设置:
```csharp
var browser = new ChromiumWebBrowser();
browser.RequestHandler = new CustomRequestHandler();
```
阅读全文