禁止WebBrowser控件弹出对话框

 

一、屏蔽alert、confirm、showModalDialog源代码:

例1、先引用COM组建mshtml;

引用名称空间mshtml:

using mshtml;

然后处理WebBrowser控件的Navigated事件,代码如下:

 

  1. private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)   
  2.          {   
  3.              IHTMLWindow2 win = (IHTMLWindow2)webBrowser1.Document.Window.DomWindow;   
  4.             string s = "window.alert = null;\r\nwindow.confirm = null;\r\nwindow.open = null;\r\nwindow.showModalDialog = null;";   
  5.              win.execScript(s, "javascript");   
  6.    }   

private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { IHTMLWindow2 win = (IHTMLWindow2)webBrowser1.Document.Window.DomWindow; string s = "window.alert = null;\r\nwindow.confirm = null;\r\nwindow.open = null;\r\nwindow.showModalDialog = null;"; win.execScript(s, "javascript"); }

例2、

我们在使用WebBrowser得到网页代码模拟操作的时候,常常会因为目标网页有弹出对话框(alert、confirm)而中断我们操作,网上也有关于屏蔽这些对话框的介绍,比如另开一线程来定时确定,或是采用FindWindow等方法来进行关闭对话框,但这些办法给人感觉总有点烦琐;其实我们只要在目标网页中重载alert和confirm函数,让它们一直都返回true,那就ok拉,下面我们来说说在.net2.0中如何实现:

该办法要用到IHTMLWindow2类,所以我们要先添加一个引用:在项目引用里面选择COM选项卡,添加Microsoft HTML Object Library,然后在我们的cs文件中引如名称空间:mshtml;

然后取得我们目标页面的HtmlDocument,比如:
HtmlDocument hd = webBrowser1.Document.Window.Frames[0].Document;

接着进行最重要的一步,重载alert,confirm函数:
IHTMLWindow2 win = (IHTMLWindow2)hd.Window.DomWindow;
string s = @"function confirm() {";
s += @"return true;";
s += @"}";
s += @"function alert() {}";
win.execScript(s, "javascript");

OK ,大功告成,我们可以继续我们正常的操作拉,比如填写表单并提交:

hd.All["username"].SetAttribute("value","username");
hd.All["password"].SetAttribute("value","password");
hd.All["buttom"].InvokeMember("click");

运行一下,烦人的alert和confirm总算不见了

二、关闭调试对话框:

处理webbrowser的NewWindow事件,设定其传入的参数Cancel=false即可。

来自: http://hi.baidu.com/fangqm/blog/item/2906a134fc718dbbd1a2d326.html

 

原文地址:https://www.cnblogs.com/zzh1236/p/1897712.html