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 简单包装  查看

 

到此我们的工作就已经完成,可以直接运行程序进行测试了
---------------------
作者:zhang116868
来源:CSDN
原文:https://blog.csdn.net/zhang116868/article/details/46945973
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2018-12-27 14:13  来自农村的Peter  阅读(673)  评论(0编辑  收藏  举报