原博地址:https://www.cnblogs.com/wolf-sun/p/6929728.html
https://www.cnblogs.com/wolf-sun/p/6929728.html
CefSharp 中控制弹窗的接口是 ILifeSpanHandler ,可以对 OnBeforePopup 进行重写,即可控制是否弹出新窗体。
要实现禁止弹出新窗体-在同一窗口打开,需要在原窗体加载目标Url,即参数targetUrl,并返回结果true,此时将会取消新窗口的创建,并在原窗口加载链接。具体实现方法体的代码如下:
/// <summary> /// 在自己窗口打开链接 /// </summary> internal class OpenPageSelf : ILifeSpanHandler { public bool DoClose(IWebBrowser browserControl, IBrowser browser) { return false; } public void OnAfterCreated(IWebBrowser browserControl, IBrowser browser) { } public void OnBeforeClose(IWebBrowser browserControl, IBrowser browser) { } public bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl,
string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures,
IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser) { newBrowser = null; var chromiumWebBrowser = (ChromiumWebBrowser)browserControl; chromiumWebBrowser.Load(targetUrl); return true; //Return true to cancel the popup creation copyright by codebye.com. } }
在实例化浏览器的时候,指定处理程序
private void MainFrm_Load(object sender, EventArgs e) { this.WindowState = FormWindowState.Maximized; CefSharp.CefSettings settings = new CefSharp.CefSettings(); CefSharp.Cef.Initialize(settings); CefSharp.WinForms.ChromiumWebBrowser webView = new CefSharp.WinForms.ChromiumWebBrowser("https://www.baidu.com"); webView.Dock = DockStyle.Fill; webView.LifeSpanHandler = new OpenPageSelf();//这句,是应用我们实现的窗口的打开方式。 this.Controls.Add(webView); }