I you worked with the WebBrowser control you probably met the following popup:


script error


I have started to use the WPF WebBrowser control in some of my applications but when I tried to disable the script errors I had a small problem the property WebBrowser.ScriptErrorsSuppressed  was not there, bummer…


After some research I have come up with a new solution. It involves injecting each webpage we display a small piece of JavaScript which catches those errors and ignores them.

Here is how it is done:

This is the java script we are injecting:

   1: function noError() 

   2: {

   3:     return true;

   4: } 

   5: window.onerror = noError;

And now The way to inject the script to the WebBrowser control:

   1: private void InjectDisableErrorScript()

   2: {

   3:     var doc = Browser.Document as HTMLDocument;

   4:     if (doc != null)

   5:     {

   6:         //Create the sctipt element

   7:         var scriptErrorSuppressed = (IHTMLScriptElement)doc.createElement("SCRIPT");

   8:         scriptErrorSuppressed.type = "text/javascript";

   9:         scriptErrorSuppressed.text = m_disableScriptError;

  10:         //Inject it to the head of the page

  11:         IHTMLElementCollection nodes = doc.getElementsByTagName("head");

  12:         foreach (IHTMLElement elem in nodes)

  13:         {

  14:             var head = (HTMLHeadElement)elem;

  15:             head.appendChild((IHTMLDOMNode)scriptErrorSuppressed);

  16:         }

  17:     }

  18: }

Don’t forget to do this every time before you navigate.

That’s it! Now you are script error free.





Tags :

2 Responses to “How to Suppress / Disable Script Errors in WPF WebBrowser Control”

  1. Justin

    Said on February 24, 2012 :

    Good to see some new posts on the site. Nice new design too.

  2. Amit

    Said on February 26, 2012 :

    Thanks Justin!

Post a Comment