CEF Xilium.CefGlue 在当前窗体中打开全部链接(防止弹窗)
我们在使用Xilium.CefGlue编写浏览器应用程序时。对于嵌入的网页假设有链接会在新窗体打开。这种用户体验会非常差。因此我们须要改动程序,使全部链接都在当前窗体中打开。
首先引用Xilium.CefGlue.dll文件。须要继承Xilium.CefGlue 中的CefLifeSpanHandler类
namespace Xilium.CefGlue { // 摘要: // Implement this interface to handle events related to browser life span. The // methods of this class will be called on the UI thread unless otherwise indicated. public abstract class CefLifeSpanHandler
继承CefLifeSpanHandler类。并重写OnBeforePopup方法,实现例如以下:
internal sealed class CwbLifeSpanHandler : CefLifeSpanHandler { private ChromeWebBrowser webBrowser; public CwbLifeSpanHandler(ChromeWebBrowser browser) { webBrowser = browser; } protected override void OnAfterCreated(CefBrowser browser) { base.OnAfterCreated(browser); webBrowser.OnCreated(browser); } protected override bool DoClose(CefBrowser browser) { return false; } protected override bool OnBeforePopup(CefBrowser browser, CefFrame frame, string targetUrl, string targetFrameName, CefWindowOpenDisposition targetDisposition, bool userGesture, CefPopupFeatures popupFeatures, CefWindowInfo windowInfo, ref CefClient client, CefBrowserSettings settings, ref bool noJavascriptAccess) { bool res = false; if (!string.IsNullOrEmpty(targetUrl)) { if (webBrowser.selfRequest != null) { CefRequest req = CefRequest.Create(); req.FirstPartyForCookies = webBrowser.selfRequest.FirstPartyForCookies; req.Options = webBrowser.selfRequest.Options; System.Collections.Specialized.NameValueCollection h = new System.Collections.Specialized.NameValueCollection(); h.Add("Content-Type", "application/x-www-form-urlencoded"); req.Set(targetUrl, webBrowser.selfRequest.Method, null, webBrowser.selfRequest.GetHeaderMap()); webBrowser.selfRequest = req; } //在该处实现用当前页面打开全部新开的窗体 webBrowser.OpenUrl(targetUrl); res = true; if (res) return res; } return base.OnBeforePopup(browser, frame, targetUrl, targetFrameName, targetDisposition, userGesture, popupFeatures, windowInfo, ref client, settings, ref noJavascriptAccess); return res; } }
尽管改动了浏览器的新窗体处理方法,但浏览器并不会自己主动载入到我们的CwbCefLifeSpanHandler类,接下来我们须要在实现CefClient的ClientBrowser类中加上我们的CwbCefLifeSpanHandler实现类:
public sealed class ClientBrowser : CefClient { private readonly CwbLifeSpanHandler _lifeSpanHandler; private ChromeWebBrowser webBrowser; public ClientBrowser(ChromeWebBrowser browser) { webBrowser = browser; _lifeSpanHandler = new CwbLifeSpanHandler(browser); } public override CefLifeSpanHandler GetLifeSpanHandler() { return _lifeSpanHandler; } }
ChromeWebBrowser是我自己对Browser的包装,
大家能够去下载实例: CEF Xilium.CefGlue 简单包装 查看
到此我们的工作就已经完毕,能够直接执行程序进行測试了