<p>I have a .NET <strong>2.0</strong> WebBrowser control used to navigate some pages with no user interaction (don't ask...long story).  Because of the user-less nature of this application, I have set the WebBrowser control's ScriptErrorsSuppressed property to true, which the documentation included with VS 2005 states will [...]"hide all its dialog boxes that originate from the underlying ActiveX control, not just script errors." The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.scripterrorssuppressed(VS.80).aspx" rel="noreferrer">MSDN article</a> doesn't mention this, however.
I have managed to cancel the NewWindow event, which prevents popups, so that's taken care of.</p>

<p>Anyone have any experience using one of these and successfully blocking <strong>all</strong> dialogs, script errors, etc?</p>

<p><strong>EDIT</strong></p>

<p>This isn't a standalone instance of IE, but an instance of a WebBrowser control living on a Windows Form application.  Anyone have any experience with this control, or the underlying one, <strong>AxSHDocVW</strong>?</p>

<p><strong>EDIT again</strong></p>

<p>Sorry I forgot to mention this... I'm trying to block a <strong>JavaScript alert()</strong>, with just an OK button.  Maybe I can cast into an IHTMLDocument2 object and access the scripts that way, I've used MSHTML a little bit, anyone know?</p>

[{'answer_id': 98543, 'author': 'William', 'author_id': 14829, 'author_profile': 'https://Stackoverflow.com/users/14829', 'pm_score': 0, 'selected': False, 'text': "<p>Are you trying to implement a web robot? I have little experience in using the hosted IE control but I did completed a few Win32 projects tried to use the IE control. Disabling the popups should be done via the event handlers of the control as you already did, but I found that you also need to change the 'Disable script debugging xxxx' in the IE options (or you could modify the registry in your codes) as cjheath already pointed out. However I also found that extra steps needed to be done on checking the navigating url for any downloadable contents to prevent those open/save dialogs. But I do not know how to deal with streaming files since I cannot skip them by looking at the urls alone and in the end I turned to the Indy library saving me all the troubles in dealing with IE. Finally, I remember Microsoft did mention something online that IE is not designed to be used as an OLE control. According to my own experience, every time the control navigates to a new page did introduce memory leaks for the programs!</p>\n"}, {'answer_id': 101632, 'author': 'David Mohundro', 'author_id': 4570, 'author_profile': 'https://Stackoverflow.com/users/4570', 'pm_score': 4, 'selected': True, 'text': '<p>This is most definitely hacky, but if you do any work with the WebBrowser control, you\'ll find yourself doing a lot of hacky stuff.</p>\n\n<p>This is the easiest way that I know of to do this. You need to inject JavaScript to override the alert function... something along the lines of injecting this JavaScript function:</p>\n\n<pre><code>window.alert = function () { }\n</code></pre>\n\n<p>There are <em>many ways to do this</em>, but it is very possible to do. One possibility is to hook an implementation of the <a href="http://msdn.microsoft.com/en-us/library/aa768283.aspx" rel="noreferrer">DWebBrowserEvents2</a> interface. Once this is done, you can then plug into the NavigateComplete, the DownloadComplete, or the DocumentComplete (or, as we do, some variation thereof) and then call an InjectJavaScript method that you\'ve implemented that performs this overriding of the window.alert method.</p>\n\n<p>Like I said, hacky, but it works :)</p>\n\n<p>I can go into more details if I need to.</p>\n'}, {'answer_id': 110048, 'author': 'Jim Crafton', 'author_id': 9864, 'author_profile': 'https://Stackoverflow.com/users/9864', 'pm_score': 3, 'selected': False, 'text': '<p>You may have to customize some things, take a look at <code>IDocHostUIHandler</code>, and then check out some of the other related interfaces. You can have a fair amount of control, even to the point of customizing dialog display/ui (I can\'t recall which interface does this). I\'m pretty sure you can do what you want, but it does require mucking around in the internals of <code>MSHTML</code> and being able to implement the various <code>COM</code> interfaces.</p>\n\n<p>Some other ideas:\n<a href="http://msdn.microsoft.com/en-us/library/aa770041.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa770041.aspx</a></p>\n\n<pre><code>IHostDialogHelper\nIDocHostShowUI\n</code></pre>\n\n<p>These may be the things you\'re looking at implementing.</p>\n'}, {'answer_id': 251524, 'author': 'Sire', 'author_id': 2440, 'author_profile': 'https://Stackoverflow.com/users/2440', 'pm_score': 4, 'selected': False, 'text': '<p>And for an easy way to inject that magic line of javascript, read <a href="https://stackoverflow.com/questions/153748/webbrowser-control-from-net-how-to-inject-javascript">how to inject javascript into webbrowser control</a>.</p>\n\n<p>Or just use this complete code: </p>\n\n<pre><code>private void InjectAlertBlocker() {\n    HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];\n    HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");\n    string alertBlocker = "window.alert = function () { }";\n    scriptEl.SetAttribute("text", alertBlocker);\n    head.AppendChild(scriptEl);\n}\n</code></pre>\n'}, {'answer_id': 330495, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I managed to inject the code above by creating an extended <code>WebBroswer</code> class and overriding the <code>OnNavigated</code> method.\n<br /><br />\nThis seemed to work quite well:\n<br /></p>\n\n<pre><code>class WebBrowserEx : WebBrowser\n{\n  public WebBrowserEx ()\n  {\n  }\n\n  protected override void OnNavigated( WebBrowserNavigatedEventArgs e )\n  {\n       HtmlElement he = this.Document.GetElementsByTagName( "head" )[0];\n       HtmlElement se = this.Document.CreateElement( "script" );\n       mshtml.IHTMLScriptElement element = (mshtml.IHTMLScriptElement)se.DomElement;\n       string alertBlocker = "window.alert = function () { }";\n       element.text = alertBlocker;\n       he.AppendChild( se );\n       base.OnNavigated( e );\n  }\n}\n</code></pre>\n'}, {'answer_id': 5780448, 'author': 'abobjects.com', 'author_id': 618173, 'author_profile': 'https://Stackoverflow.com/users/618173', 'pm_score': 2, 'selected': False, 'text': '<p>The <code>InjectAlertBlocker</code> is absolutely correct\ncode is </p>\n\n<pre><code>private void InjectAlertBlocker() {\n    HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];\n    HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");\n    IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\n    string alertBlocker = "window.alert = function () { }";\n    element.text = alertBlocker;\n    head.AppendChild(scriptEl);\n}\n</code></pre>\n\n<p>References needed to be added is </p>\n\n<ol>\n<li><p>Add a reference to <code>MSHTML</code>, which will probalby be called "<strong>Microsoft HTML Object Library</strong>" under <code>COM</code> references.</p></li>\n<li><p>Add <code>using mshtml;</code> to your namespaces.</p></li>\n<li><p>Get a reference to your script element\'s <code>IHTMLElement</code>:</p></li>\n</ol>\n\n<p>Then you can use the <code>Navigated</code> event of webbrowser as:</p>\n\n<pre><code>private void InjectAlertBlocker()\n{\n    HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];\n    HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");\n    IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\n    string alertBlocker = "window.alert = function () { }";\n    element.text = alertBlocker;\n    head.AppendChild(scriptEl);\n}\n\nprivate void webDest_Navigated(object sender, WebBrowserNavigatedEventArgs e)\n{\n    InjectAlertBlocker();\n}\n</code></pre>\n'}, {'answer_id': 7903067, 'author': 'Prashant Bassi', 'author_id': 1014615, 'author_profile': 'https://Stackoverflow.com/users/1014615', 'pm_score': 2, 'selected': False, 'text': '<pre><code>webBrowser1.ScriptErrorsSuppressed = true;\n</code></pre>\n\n<p>Just add that to your entry level function. After alot of research is when I came across this method, and touch wood till now its worked. Cheers!!</p>\n'}, {'answer_id': 9412021, 'author': 'Legoless', 'author_id': 573186, 'author_profile': 'https://Stackoverflow.com/users/573186', 'pm_score': 0, 'selected': False, 'text': '<p>I had bigger problems with this: loading a webpage that is meant for printing and it displays annoying Print dialog. The InjectBlocker was the only way that worked, but fairly unreliable. Under certain conditions (I am considering it\'s due that WebBrowser control uses IE engine and this depends on installed IE version) the print dialog still appears. This is a major problem, the solution works on Win7 with IE9 installed, but WinXP with IE8 displays the dialog, no matter what.</p>\n\n<p>I believe the solution is in modifying source code and removing the print javascript, before control renders the page. However I tried that with: DocumentText property of the webbrowser control and it is not working. The property is not read only, but it has no effect, when I modify the source.</p>\n\n<p>The solution I found for my problem is the Exec script:</p>\n\n<pre><code>string alertBlocker = "window.print = function emptyMethod() { }; window.alert = function emptyMethod() { }; window.open = function emptyMethod() { };";    \nthis.Document.InvokeScript("execScript", new Object[] { alertBlocker, "JavaScript" });\n</code></pre>\n'}, {'answer_id': 9812051, 'author': 'Harry', 'author_id': 126537, 'author_profile': 'https://Stackoverflow.com/users/126537', 'pm_score': 3, 'selected': False, 'text': '<p>Bulletproof alert blocker:</p>\n\n<pre><code>Browser.Navigated +=\n    new WebBrowserNavigatedEventHandler(\n        (object sender, WebBrowserNavigatedEventArgs args) =&gt; {\n            Action&lt;HtmlDocument&gt; blockAlerts = (HtmlDocument d) =&gt; {\n                HtmlElement h = d.GetElementsByTagName("head")[0];\n                HtmlElement s = d.CreateElement("script");\n                IHTMLScriptElement e = (IHTMLScriptElement)s.DomElement;\n                e.text = "window.alert=function(){};";\n                h.AppendChild(s);\n            };\n            WebBrowser b = sender as WebBrowser;\n            blockAlerts(b.Document);\n            for (int i = 0; i &lt; b.Document.Window.Frames.Count; i++)\n                try { blockAlerts(b.Document.Window.Frames[i].Document); }\n                catch (Exception) { };\n        }\n    );\n</code></pre>\n\n<p>This sample assumes you have <em>Microsoft.mshtml</em> reference added, "<em>using mshtml;</em>" in your namespaces and <em>Browser</em> is your <em>WebBrowser</em> instance.</p>\n\n<p>Why is it bulletproof? First, it <strong>handles scripts inside frames</strong>. Then, it <strong>doesn\'t crash</strong> when a special <em>"killer frame"</em> exists in document. A <em>"killer frame"</em> 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.</p>\n\n<p>Maybe it\'s not the most readable piece of code, but it works with real life, ill-formed pages.</p>\n'}, {'answer_id': 14669921, 'author': 'volody', 'author_id': 241811, 'author_profile': 'https://Stackoverflow.com/users/241811', 'pm_score': 2, 'selected': False, 'text': '<p>window.showModelessDialog and window.showModalDialog can be blocked by implementing INewWindowManager interface, additionally code below show how to block alert dialogs by implementing IDocHostShowUI</p>\n\n<pre><code>public class MyBrowser : WebBrowser\n{\n\n    [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]\n    public MyBrowser()\n    {\n    }\n\n    protected override WebBrowserSiteBase CreateWebBrowserSiteBase()\n    {\n        var manager = new NewWindowManagerWebBrowserSite(this);\n        return manager;\n    }\n\n    protected class NewWindowManagerWebBrowserSite : WebBrowserSite, IServiceProvider, IDocHostShowUI\n    {\n        private readonly NewWindowManager _manager;\n\n        public NewWindowManagerWebBrowserSite(WebBrowser host)\n            : base(host)\n        {\n            _manager = new NewWindowManager();\n        }\n\n        public int ShowMessage(IntPtr hwnd, string lpstrText, string lpstrCaption, int dwType, string lpstrHelpFile, int dwHelpContext, out int lpResult)\n        {\n            lpResult = 0;\n            return Constants.S_OK; //  S_OK Host displayed its UI. MSHTML does not display its message box.\n        }\n\n        // Only files of types .chm and .htm are supported as help files.\n        public int ShowHelp(IntPtr hwnd, string pszHelpFile, uint uCommand, uint dwData, POINT ptMouse, object pDispatchObjectHit)\n        {\n            return Constants.S_OK; //  S_OK Host displayed its UI. MSHTML does not display its message box.\n        }\n\n        #region Implementation of IServiceProvider\n\n        public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject)\n        {\n            if ((guidService == Constants.IID_INewWindowManager &amp;&amp; riid == Constants.IID_INewWindowManager))\n            {\n                ppvObject = Marshal.GetComInterfaceForObject(_manager, typeof(INewWindowManager));\n                if (ppvObject != IntPtr.Zero)\n                {\n                    return Constants.S_OK;\n                }\n            }\n            ppvObject = IntPtr.Zero;\n            return Constants.E_NOINTERFACE;\n        }\n\n        #endregion\n    }\n }\n\n[ComVisible(true)]\n[Guid("01AFBFE2-CA97-4F72-A0BF-E157038E4118")]\npublic class NewWindowManager : INewWindowManager\n{\n    public int EvaluateNewWindow(string pszUrl, string pszName,\n        string pszUrlContext, string pszFeatures, bool fReplace, uint dwFlags, uint dwUserActionTime)\n    {\n\n        // use E_FAIL to be the same as CoInternetSetFeatureEnabled with FEATURE_WEBOC_POPUPMANAGEMENT\n        //int hr = MyBrowser.Constants.E_FAIL; \n        int hr = MyBrowser.Constants.S_FALSE; //Block\n        //int hr = MyBrowser.Constants.S_OK; //Allow all\n        return hr;\n    }\n}\n</code></pre>\n'}, {'answer_id': 35044129, 'author': 'Marym Nor Marym Nor', 'author_id': 5848168, 'author_profile': 'https://Stackoverflow.com/users/5848168', 'pm_score': 0, 'selected': False, 'text': '<p>Simply from the browser control properties: scriptErrorSupressed=true</p>\n'}, {'answer_id': 36258414, 'author': 'IsLeadByte', 'author_id': 6123304, 'author_profile': 'https://Stackoverflow.com/users/6123304', 'pm_score': 0, 'selected': False, 'text': '<p>The easiest way to do this is : \nIn the : Webbrowser Control you have the procedure ( standard ) <code>BeforeScriptExecute</code> </p>\n\n<p>( The parameter for <code>BeforeScriptExecute</code> is <code>pdispwindow</code> )</p>\n\n<p>Add this :</p>\n\n<pre><code>pdispwindow.execscript("window.alert = function () { }")\n</code></pre>\n\n<p>In this way before any script execution on the page window alert will be suppressed by injected code.</p>\n'}]
['https://Stackoverflow.com/questions/77659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13791/']