您需要创建一个实现 IRequestHandler
接口的类,然后将该类的实例设置为浏览器对象中的RequestHandler
。
从版本 53 开始,该类应如下所示:
class ChromeBrowserRequestHandler: IRequestHandler
{
public bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
{
return false;
}
public bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool isRedirect)
{
return false;
}
public bool OnBeforePluginLoad(IWebBrowser browser, string url, string policyUrl, WebPluginInfo info)
{
return false;
}
public CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
{
var headers = request.Headers;
headers["Custom-Header"] = "My Custom Header";
request.Headers = headers;
return CefReturnValue.Continue;
}
public bool OnCertificateError(IWebBrowser browser, CefErrorCode errorCode, string requestUrl)
{
return false;
}
public void OnPluginCrashed(IWebBrowser browser, string pluginPath)
{
}
public void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status)
{
}
public IResponseFilter GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
{
return null;
}
public bool OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
{
return false;
}
public bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
{
return false;
}
public void OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath)
{
}
public bool OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url)
{
return false;
}
public bool OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback)
{
return false;
}
public void OnRenderViewReady(IWebBrowser browserControl, IBrowser browser)
{
}
public void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
{
}
public void OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, ref string newUrl)
{
}
public bool OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
{
return false;
}
}
然后,在创建您的浏览器对象时:
ChromiumWebBrowser myBrowser = new ChromiumWebBrowser("whatever.com")
{
RequestHandler = new ChromeBrowserRequestHandler()
};
请注意,在加载页面之前必须设置请求处理程序。如果您无法在实例化期间设置请求处理程序,则仍然可以稍后设置它并使用
myBrowser.Load("whatever.com")
重新加载页面。