posts - 103,  comments - 6,  views - 14万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

 

一、屏蔽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

 

posted on   也风  阅读(2967)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示