2012-09-13 32 views
5

在VS 2010中使用webbrowser控件开发Windows Forms应用程序。 我的目标是在这个网站上自动导航,但是当我在某个点上时,网站会弹出一个JavaScript警报,这将停止自动化,直到我按下OK按钮。 我有点解决了这个问题,通过模拟输入按下时弹出,但应用程序应该保持专注,以便它的工作。 我的问题是,有没有什么办法可以从网站上杀死这个自定义的javascript警报(我没有访问到一边,从客户端杀死它),所以它没有显示或任何其他方式来解决这个问题? 显示的javascript警报(messagebox)不是错误,是由于某种原因该网站的程序员放在那里的JavaScript警报。webBrowser控制停止来自网站的JavaScript警报

+1

有点谷歌搜索发现:http://josheinstein.com/blog/index.php/2010/01/webbrowser-control-prevent-window-alert/ –

回答

0

您可以尝试在页面加载之前使用Navigated事件并拦截DocumentText以删除alert(...);引用。

Navigated页面上的MSDN:

处理的Navigated事件时接收通知的WebBrowser控制导航到一个新的文档。发生Navigated事件时,新文档已开始加载,这意味着您可以通过DocumentDocumentTextDocumentStream属性访问加载的内容。

下面是一些代码:

using System.Windows.Forms; 
using System.Text.RegularExpressions; 

namespace Your.App 
{ 
    public class PopupSuppress 
    { 
     WebBrowser _wb; 
     public PopupSupress() 
     { 
      _wb = new WebBrowser(); 
      _wb.Navigated += new WebBrowserNavigatedEventHandler(_wb_Navigated); 
     } 

     void _wb_Navigated(object sender, WebBrowserNavigatedEventArgs e) 
     { 
      string alertRegexPattern = "alert\\([\\s\\S]*\\);"; 
      //make sure to only write to _wb.DocumentText if there is a change. 
      //This will prompt a reloading of the page (and another 'Navigated' event) [see MSDN link] 
      if(Regex.IsMatch(_wb.DocumentText, alertRegexPattern)) 
       _wb.DocumentText = Regex.Replace(_wb.DocumentText, alertRegexPattern, string.Empty); 
     } 
    } 
} 

来源/资源: