System.Windows.Forms.WebBrowser wb; //WebBrowser 对象
wb.NewWindow += new CancelEventHandler(wb_NewWindow);
wb.DocumentCompleted += delegate
{
#region 处理window.open新开窗口的问题
System.Windows.Forms.HtmlElement html = wb.Document.CreateElement("div");
html.InnerHtml += "<a id=\"popLink\" href=\"\" target=\"_blank\" style=\"display:none;\"></a>";
wb.Document.Body.AppendChild(html);
string jsHtml = "";
jsHtml += "window.open=function(url, title, prop) ";
jsHtml += "{";
jsHtml += "obj = document.getElementById('popLink'); ";
jsHtml += "obj.style.display='block'; ";
jsHtml += "obj.href=url; ";
jsHtml += "obj.focus(); ";
jsHtml += "obj.click(); ";
jsHtml += "obj.style.display='none' ";
jsHtml += "} ";
mshtml.IHTMLDocument2 doc = wb.Document.DomDocument as mshtml.IHTMLDocument2;
mshtml.IHTMLWindow2 win = doc.parentWindow as mshtml.IHTMLWindow2;
win.execScript(jsHtml, "javascript");
#endregion
};
static void wb_NewWindow(object sender, CancelEventArgs e)
{
System.Windows.Forms.WebBrowser web = (System.Windows.Forms.WebBrowser)sender;
string newUrl = web.StatusText.ToString();
showNewWinWithUrlInner(null, newUrl, "", 800, 600, true, false);//自己取到新窗口url后自行处理
e.Cancel = true;
}
C# WebBrowser 取 window.open 新窗口 url的方法
最新推荐文章于 2024-09-11 15:33:18 发布
这段代码展示了如何使用C#处理`System.Windows.Forms.WebBrowser`控件中遇到的`window.open`新开窗口的问题。通过注册事件监听器和修改JavaScript,将新开窗口的逻辑控制在当前页面内,避免了新窗口的弹出,并提供了自定义的新开窗口处理方法。
摘要由CSDN通过智能技术生成