【问题标题】:Supress the "are you sure you want to leave this page" popup in the .NET webbrowser control抑制 .NET webbrowser 控件中的“您确定要离开此页面”弹出窗口
【发布时间】:2012-05-08 02:05:37
【问题描述】:

我有一个用 WinForms C# 编写的 Web 浏览器自动化项目。 在导航过程中,浏览器会执行“您确定要离开此页面吗?”。弹出窗口。 我们需要这个弹出窗口,所以我无法从网站代码中删除它,这意味着我必须在我的自动化应用程序中覆盖它。

有人知道怎么做吗?

【问题讨论】:

  • 好的,我通过让后台线程休眠一秒钟然后执行 sendkeys.sendwait("{ENTER}") 解决了这个问题

标签: c# winforms webbrowser-control


【解决方案1】:

这是顺利的解决方案..

添加对 mshtml 的引用并使用 mshtml 添加;

Browser.Navigated += 
    new WebBrowserNavigatedEventHandler( 
        (object sender, WebBrowserNavigatedEventArgs args) => { 
            Action<HtmlDocument> blockAlerts = (HtmlDocument d) => { 
                HtmlElement h = d.GetElementsByTagName("head")[0]; 
                HtmlElement s = d.CreateElement("script"); 
                IHTMLScriptElement e = (IHTMLScriptElement)s.DomElement; 
                e.text = "window.alert=function(){};"; 
                h.AppendChild(s); 
            }; 
            WebBrowser b = sender as WebBrowser; 
            blockAlerts(b.Document); 
            for (int i = 0; i < b.Document.Window.Frames.Count; i++) 
                try { blockAlerts(b.Document.Window.Frames[i].Document); } 
                catch (Exception) { }; 
        } 
    ); 

【讨论】:

  • 我实际上已经在我对某处某个问题的回答中提供了一个答案(我是编写“WebBrowser Control Limitations”的人)。如果我可以问,您的应用的目的是什么?
  • 另外,您是否通过 window.alert=function(){} 找到了我的答案;在里面还是有其他人也写过这个?
【解决方案2】:

您能否对网站代码进行任何更改?

如果是这样,您可能会考虑通过 ObjectForScripting 公开对象,然后在决定显示弹出窗口之前让网站代码检查 window.external(并可能询问您的对象) - 所以如果它找不到您的对象,它假定它正在正常使用并显示它。

【讨论】:

【解决方案3】:

不再需要添加。试试吧。像魅力一样工作。 ^_^

private void webNavigated(object sender, WebBrowserNavigatedEventArgs e)
    {
        HtmlDocument doc = webBrowser.Document;
        HtmlElement head = doc.GetElementsByTagName("head")[0];
        HtmlElement s = doc.CreateElement("script");
        s.SetAttribute("text", "function cancelOut() { window.onbeforeunload = null; window.alert = function () { }; window.confirm=function () { }}");
        head.AppendChild(s);
        webBrowser.Document.InvokeScript("cancelOut");
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多