Supress the “are you sure you want to leave this page” popup in the .NET webbrowser control

断了今生、忘了曾经 提交于 2019-12-23 05:24:07

问题


I have a web browser automation project written in WinForms C#. During the navigation there is a point where the browser does the "are you sure you want to leave this page?" popup. We need this popup, so I cannot remove it from the website code, which means I have to override it in my automation app.

Does anyone have an idea how to do this?


回答1:


and here was the smooth solution..

add a reference to mshtml and add using 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) { }; 
        } 
    ); 



回答2:


Are you able to make any changes to the website code?

If so, you might look at exposing an object through ObjectForScripting, then having the website code check window.external (and possibly interrogating your object) before it decides to display the popup - so if it can't find your object, it assumes it's being used normally and shows it.




回答3:


Don't need add anymore. Try it. Work like a charm. ^_^

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");
    }


来源:https://stackoverflow.com/questions/10348692/supress-the-are-you-sure-you-want-to-leave-this-page-popup-in-the-net-webbrow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!