项目使用的CefSharp内嵌在Winform中,希望实现的目标是将请求网址重定向到新的Url地址。查阅 CefSharp 的接口定义后,发现实现 IRequestHandler 接口即可解决此需求。
这里展示 CefSharp 45 版本的IRequestHandler接口定义:
public interface IRequestHandler
{
bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback);
bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool isRedirect);
CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback); //codebye.com原创
bool OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback);
bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture);
void OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath);
bool OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url);
bool OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback);
void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status);
void OnRenderViewReady(IWebBrowser browserControl, IBrowser browser);
void OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, ref string newUrl);
bool OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response);
}
实现目标需求主要是实现 IRequestHandler.OnBeforeResourceLoad 方法,这里仅提供重定向方法的实现片段。具体实现 可参考 CefSharp 源码附带的示例Demo。
CefReturnValue IRequestHandler.OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame,
IRequest request, IRequestCallback callback)
{
//NOTE: If you do not wish to implement this method returning false is the default behaviour
// We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
//callback.Dispose();
//return false;
//NOTE: When executing the callback in an async fashion need to check to see if it’s disposed
if (!callback.IsDisposed)
{
using (callback)
{
//Note to Redirect simply set the request Url , write by codebye
if (request.Url.Contains(“http://www.12306.cn/mormhweb/images/global20150101.css”))
{
//如果替换Css文件,这里需要注意到是:如果原链接是https的Url,则替换后的Url也需要是Https的,否则Css无法生效。
request.Url = “https://rescdn.qqmail.com/zh_CN/htmledition/style/webp/comm20103272bfb.css”;
}
//Callback in async fashion
callback.Continue(true);
return CefReturnValue.ContinueAsync;
}
}
return CefReturnValue.Continue;
}
调用方法:myBrowser.RequestHandler = new CefListenRequestHandler();
如此设置后,即可实现Url重定向到新的Url。原创文章,Codebye.com所有, 禁止转载