Blocking dialogs in .NET WebBrowser control

前端 未结 12 1311
执笔经年
执笔经年 2020-11-27 17:04

I have a .NET 2.0 WebBrowser control used to navigate some pages with no user interaction (don\'t ask...long story). Because of the user-less nature of thi

12条回答
  •  半阙折子戏
    2020-11-27 17:24

    Bulletproof alert blocker:

    Browser.Navigated +=
        new WebBrowserNavigatedEventHandler(
            (object sender, WebBrowserNavigatedEventArgs args) => {
                Action 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) { };
            }
        );
    

    This sample assumes you have Microsoft.mshtml reference added, "using mshtml;" in your namespaces and Browser is your WebBrowser instance.

    Why is it bulletproof? First, it handles scripts inside frames. Then, it doesn't crash when a special "killer frame" exists in document. A "killer frame" is a frame which raises an exception on attempt to use it as HtmlWindow object. Any "foreach" used on Document.Window.Frames would cause an exception, so safer "for" loop must be used with try / catch block.

    Maybe it's not the most readable piece of code, but it works with real life, ill-formed pages.

提交回复
热议问题