C#Webbrowser中屏蔽弹出窗口及脚本错误提示
一、屏蔽脚本错误提示
当IE浏览器遇到脚本错误时浏览器,左下角会出现一个黄色图标,点击可以查看脚本错误的详细信息,并不会有弹出的错误信息框。当我们使用WebBrowser控件时有错误信息框弹出,这样程序显的很不友好,而且会让一些自动执行的程序暂停。我看到有人采取的解决方案是做一个窗体杀手程序来关闭弹出的窗体。今天探讨的方法是从控件解决问题。
1、SHDocVw.dll 在COM时代我们使用的WebBrowser控件是SHDocVw.dll。屏蔽错误信息的方法很简单使用下面的一句就可以搞定。
WebBrowser1.Silent = true;
2、.Net中
webBrowser1.ScriptErrorsSuppressed = true;
(据说在.net framework2.0以前是这样,我没有使用过) 3、上面的方法对于多个框架嵌套等等的情形还是不能很好的解决。 (SHDocVw通过引用,浏览,在C盘windows/system32/下面找到。) protected override void AttachInterfaces(object nativeActiveXObject) { Iwb2 = (SHDocVw.IWebBrowser2) nativeActiveXObject; Iwb2.Silent = true; base.AttachInterfaces(nativeActiveXObject); } protected override void DetachInterfaces() { Iwb2 = null; base.DetachInterfaces(); } }
//项目中添加Micrsoft.mshtml引用 using mshtml; private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { IHTMLDocument2 vDocument = (IHTMLDocument2)webBrowser1.Document.DomDocument; vDocument.parentWindow.execScript( "function alert(str){if(str=='zswang')confirm(str);}", "javaScript"); } //frame结构 private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { IHTMLDocument2 vDocument = (IHTMLDocument2)webBrowser1.Document.DomDocument; foreach (IHTMLElement vElement in vDocument.all) if (vElement.tagName.ToUpper() == "FRAME") { IHTMLFrameBase2 vFrameBase2 = vElement as IHTMLFrameBase2; vFrameBase2.contentWindow.execScript( "function alert(str){confirm('[' + str + ']');}", "javaScript"); } } 二、屏蔽其它窗口 (wb.ActiveXInstance as SHDocVw.WebBrowser).NavigateComplete2 += new DWebBrowserEvents2_NavigateComplete2EventHandler(wb_NavigateComplete2);//wb是一个Webbrowser控件 Q:winform中如何实现自动点击webbrowser弹出对话框中的确定按钮 A: //using mshtml; //using SHDocVw; private void Form1_Load(object sender, EventArgs e) ...{ this.webBrowser1.Navigate("http://localhost:28512/WebSite2/Default.aspx"); SHDocVw.WebBrowser wb = this.webBrowser1.ActiveXInstance as SHDocVw.WebBrowser; wb.NavigateComplete2 += new SHDocVw.DWebBrowserEvents2_NavigateComplete2EventHandler(wb_NavigateComplete2); } void wb_NavigateComplete2(object pDisp, ref object URL) ...{ mshtml.IHTMLDocument2 doc = (this.webBrowser1.ActiveXInstance as SHDocVw.WebBrowser).Document as mshtml.IHTMLDocument2; doc.parentWindow.execScript("function alert(str){return ''}", "javascript"); } |