.Net WebBrowser and ScriptErrorsSuppressed

WebBrowser.ScriptErrorsSuppressed block not only scripts but all dialogs, which can cause problems. There are several suggestions on how to resolve this:

http://www.codeproject.com/KB/cpp/ExtendedWebBrowser.aspx

http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.scripterrorssuppressed.aspx

but they did not work for me.

There is also a bug filed for not being able to only block scripts:

http://connect.microsoft.com/VisualStudio/feedback/details/434323/htmlelementerroreventhandler-cannot-work-with-webbrowser-control

I souped together something that does seem to work, but probably need some more testing before I’m sure:-)

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace FixedWeb
{
  ///
  /// Based on http://support.microsoft.com/kb/261003
  ///
  public class ExtendedWebBrowser : WebBrowser
  {
    protected class ExtendedWebBrowserSite : WebBrowserSite, IOleCommandTarget
    {
      const int OLECMDID_SHOWSCRIPTERROR = 40;
      const int OLECMDID_SHOWMESSAGE = 41;

      static Guid CGID_DocHostCommandHandler = new Guid("F38BC242-B950-11D1-8918-00C04FC2C836");

      const int S_OK = 0;
      const int OLECMDERR_E_NOTSUPPORTED = (-2147221248);
      const int OLECMDERR_E_UNKNOWNGROUP = (-2147221244);

      public ExtendedWebBrowserSite(WebBrowser wb)
        : base(wb)
      {
      }

      #region IOleCommandTarget Members
      public int QueryStatus(Guid pguidCmdGroup, int cCmds, IntPtr prgCmds, IntPtr pCmdText)
      {
        return OLECMDERR_E_NOTSUPPORTED;
      }

      public int Exec(Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
      {
        if (pguidCmdGroup == CGID_DocHostCommandHandler)
        {
          if (nCmdID == OLECMDID_SHOWSCRIPTERROR)
          {
            // do not need to alter pvaOut as the docs says, enough to return S_OK here
            return S_OK;
          }
        }

        return OLECMDERR_E_NOTSUPPORTED;
      }

      #endregion
    }

    protected override WebBrowserSiteBase CreateWebBrowserSiteBase()
    {
      return new ExtendedWebBrowserSite(this);
    }
    public ExtendedWebBrowser()
    {
    }
  }

  [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComVisible(true),
  Guid("B722BCCB-4E68-101B-A2BC-00AA00404770")]
  public interface IOleCommandTarget
  {
    [return: MarshalAs(UnmanagedType.I4)]
    [PreserveSig]
    int QueryStatus([In, MarshalAs(UnmanagedType.LPStruct)] Guid pguidCmdGroup,
      int cCmds,
      IntPtr prgCmds,
      IntPtr pCmdText);

    [return: MarshalAs(UnmanagedType.I4)]
    [PreserveSig]
    int Exec([In, MarshalAs(UnmanagedType.LPStruct)] Guid pguidCmdGroup,
      int nCmdID,
      int nCmdexecopt,
      IntPtr pvaIn,
      IntPtr pvaOut);
  }
}
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply