When using the WebBrowser control and loading a html page it is possible that a message appears that there is a javascript error. This is especially the case if the webpage has been saved from the web and is then displayed on a computer which is offline. Unfortunately there is no property on the browser control which can be used to suppress this kind of error. It is however possible to inject a script tag in the header of an loaded html-file which does catch all errors. Therefore no message will be displayed. You can use the following snippet:
private void SuppressScriptErrors(WebBrowser wb) { HTMLDocument doc = wb.Document as HTMLDocument; if (doc != null) { IHTMLScriptElement scriptErrorSuppressed = (IHTMLScriptElement)doc.createElement("SCRIPT"); scriptErrorSuppressed.type = "text/javascript"; scriptErrorSuppressed.text = @"function noError() { return true; } window.onerror = noError;"; IHTMLElementCollection nodes = doc.getElementsByTagName("head"); foreach (IHTMLElement node in nodes) { HTMLHeadElementClass head = (HTMLHeadElementClass)node; head.appendChild((IHTMLDOMNode)scriptErrorSuppressed); } } }
The injection does also work if a file like a word-document or a pdf-file is opened within the webbrowser. There won’t be an error because it is no html-file.
You might get an error (Interop type xxx cannot be embedded. Use the applicable interface instead) which can be resolved with a reference to “Microsoft HTML Object Library (MSHTML) choosing EmbedInteropTypes = False in the properties