Deshabilitar el error de JavaScript en el control WebBrowser

Estoy desarrollando una aplicación de Windows con un control WebBrowser que navega a un sitio sharepoint.
Mi problema es que estoy recibiendo un error de JavaScript.

¿Cómo puedo desactivar el error de JavaScript? No quiero que aparezcan.

webBrowser.ScriptErrorsSuppressed = true; 

Esto desactiva los errores del script y también desactiva otras ventanas … como la ventana de inicio de sesión de NTLM o la ventana de aceptación del certificado del cliente. Lo siguiente suprimirá solo los errores de javascript.

 // Hides script errors without hiding other dialog boxes. private void SuppressScriptErrorsOnly(WebBrowser browser) { // Ensure that ScriptErrorsSuppressed is set to false. browser.ScriptErrorsSuppressed = false; // Handle DocumentCompleted to gain access to the Document object. browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler( browser_DocumentCompleted); } private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { ((WebBrowser)sender).Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error); } private void Window_Error(object sender, HtmlElementErrorEventArgs e) { // Ignore the error and suppress the error dialog box. e.Handled = true; } 

Ninguna de las soluciones anteriores era adecuada para mi escenario. Los eventos .Navigation y .FileDownload parecían una buena opción, pero el acceso a la propiedad WebBrowser.Document arrojó una excepción de acceso no autorizada provocada por la seguridad de secuencias de comandos de marcos cruzados (nuestro contenido web contiene marcos, todo en el mismo dominio / dirección pero los marcos tienen sus propios agujeros de seguridad que están siendo bloqueados).

La solución que funcionó fue anular IOleCommandTarget y detectar los comandos de error de script en ese nivel. Aquí está la subclase WebBrowser para lograr esto:

 ///  /// Subclassed WebBrowser that suppresses error pop-ups. /// /// Notes. /// ScriptErrorsSuppressed property is not used because this actually suppresses *all* pop-ups. /// /// More info at: /// http://stackoverflow.com/questions/2476360/disable-javascript-error-in-webbrowser-control ///  public class WebBrowserEx : WebBrowser { #region Constructor ///  /// Default constructor. /// Initialise browser control and attach customer event handlers. ///  public WebBrowserEx() { this.ScriptErrorsSuppressed = false; } #endregion #region Overrides ///  /// Override to allow custom script error handling. ///  ///  protected override WebBrowserSiteBase CreateWebBrowserSiteBase() { return new WebBrowserSiteEx(this); } #endregion #region Inner Class [WebBrowserSiteEx] ///  /// Sub-class to allow custom script error handling. ///  protected class WebBrowserSiteEx : WebBrowserSite, NativeMethods.IOleCommandTarget { ///  /// Default constructor. ///  public WebBrowserSiteEx(WebBrowserEx webBrowser) : base (webBrowser) { } /// Queries the object for the status of one or more commands generated by user interface events. /// The GUID of the command group. /// The number of commands in . /// An array of OLECMD structures that indicate the commands for which the caller needs status information. This method fills the  member of each structure with values taken from the OLECMDF enumeration. /// An OLECMDTEXT structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information. /// This method returns S_OK on success. Other possible return values include the following. /// E_FAIL The operation failed. /// E_UNEXPECTED An unexpected error has occurred. /// E_POINTER The  argument is null. /// OLECMDERR_E_UNKNOWNGROUP The  parameter is not null but does not specify a recognized command group. public int QueryStatus(ref Guid pguidCmdGroup, int cCmds, NativeMethods.OLECMD prgCmds, IntPtr pCmdText) { if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == prgCmds.cmdID) { // Do nothing (suppress script errors) return NativeMethods.S_OK; } // Indicate that command is unknown. The command will then be handled by another IOleCommandTarget. return NativeMethods.OLECMDERR_E_UNKNOWNGROUP; } /// Executes the specified command. /// The GUID of the command group. /// The command ID. /// Specifies how the object should execute the command. Possible values are taken from the  and  enumerations. /// The input arguments of the command. /// The output arguments of the command. /// This method returns S_OK on success. Other possible return values include /// OLECMDERR_E_UNKNOWNGROUP The  parameter is not null but does not specify a recognized command group. /// OLECMDERR_E_NOTSUPPORTED The  parameter is not a valid command in the group identified by . /// OLECMDERR_E_DISABLED The command identified by  is currently disabled and cannot be executed. /// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by , but no help is available. /// OLECMDERR_E_CANCELED The user canceled the execution of the command. public int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, object[] pvaIn, int pvaOut) { if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == nCmdID) { // Do nothing (suppress script errors) return NativeMethods.S_OK; } // Indicate that command is unknown. The command will then be handled by another IOleCommandTarget. return NativeMethods.OLECMDERR_E_UNKNOWNGROUP; } } #endregion } 

~

 ///  /// Native (unmanaged) methods, required for custom command handling for the WebBrowser control. ///  public static class NativeMethods { /// From docobj.h public const int OLECMDERR_E_UNKNOWNGROUP = -2147221244; ///  /// From Microsoft.VisualStudio.OLE.Interop (Visual Studio 2010 SDK). ///  public enum OLECMDID { ///  OLECMDID_OPEN = 1, ///  OLECMDID_NEW, ///  OLECMDID_SAVE, ///  OLECMDID_SAVEAS, ///  OLECMDID_SAVECOPYAS, ///  OLECMDID_PRINT, ///  OLECMDID_PRINTPREVIEW, ///  OLECMDID_PAGESETUP, ///  OLECMDID_SPELL, ///  OLECMDID_PROPERTIES, ///  OLECMDID_CUT, ///  OLECMDID_COPY, ///  OLECMDID_PASTE, ///  OLECMDID_PASTESPECIAL, ///  OLECMDID_UNDO, ///  OLECMDID_REDO, ///  OLECMDID_SELECTALL, ///  OLECMDID_CLEARSELECTION, ///  OLECMDID_ZOOM, ///  OLECMDID_GETZOOMRANGE, ///  OLECMDID_UPDATECOMMANDS, ///  OLECMDID_REFRESH, ///  OLECMDID_STOP, ///  OLECMDID_HIDETOOLBARS, ///  OLECMDID_SETPROGRESSMAX, ///  OLECMDID_SETPROGRESSPOS, ///  OLECMDID_SETPROGRESSTEXT, ///  OLECMDID_SETTITLE, ///  OLECMDID_SETDOWNLOADSTATE, ///  OLECMDID_STOPDOWNLOAD, ///  OLECMDID_ONTOOLBARACTIVATED, ///  OLECMDID_FIND, ///  OLECMDID_DELETE, ///  OLECMDID_HTTPEQUIV, ///  OLECMDID_HTTPEQUIV_DONE, ///  OLECMDID_ENABLE_INTERACTION, ///  OLECMDID_ONUNLOAD, ///  OLECMDID_PROPERTYBAG2, ///  OLECMDID_PREREFRESH, ///  OLECMDID_SHOWSCRIPTERROR, ///  OLECMDID_SHOWMESSAGE, ///  OLECMDID_SHOWFIND, ///  OLECMDID_SHOWPAGESETUP, ///  OLECMDID_SHOWPRINT, ///  OLECMDID_CLOSE, ///  OLECMDID_ALLOWUILESSSAVEAS, ///  OLECMDID_DONTDOWNLOADCSS, ///  OLECMDID_UPDATEPAGESTATUS, ///  OLECMDID_PRINT2, ///  OLECMDID_PRINTPREVIEW2, ///  OLECMDID_SETPRINTTEMPLATE, ///  OLECMDID_GETPRINTTEMPLATE } ///  /// From Microsoft.VisualStudio.Shell (Visual Studio 2010 SDK). ///  public const int S_OK = 0; ///  /// OLE command structure. ///  [StructLayout(LayoutKind.Sequential)] public class OLECMD { ///  /// Command ID. ///  [MarshalAs(UnmanagedType.U4)] public int cmdID; ///  /// Flags associated with cmdID. ///  [MarshalAs(UnmanagedType.U4)] public int cmdf; } ///  /// Enables the dispatching of commands between objects and containers. ///  [ComVisible(true), Guid("B722BCCB-4E68-101B-A2BC-00AA00404770"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IOleCommandTarget { /// Queries the object for the status of one or more commands generated by user interface events. /// The GUID of the command group. /// The number of commands in . /// An array of  structures that indicate the commands for which the caller needs status information. /// An  structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information. /// This method returns S_OK on success. Other possible return values include the following. /// E_FAIL The operation failed. /// E_UNEXPECTED An unexpected error has occurred. /// E_POINTER The  argument is null. /// OLECMDERR_E_UNKNOWNGROUPThe  parameter is not null but does not specify a recognized command group. [PreserveSig] [return: MarshalAs(UnmanagedType.I4)] int QueryStatus(ref Guid pguidCmdGroup, int cCmds, [In] [Out] NativeMethods.OLECMD prgCmds, [In] [Out] IntPtr pCmdText); /// Executes the specified command. /// The GUID of the command group. /// The command ID. /// Specifies how the object should execute the command. Possible values are taken from the  and  enumerations. /// The input arguments of the command. /// The output arguments of the command. /// This method returns S_OK on success. Other possible return values include /// OLECMDERR_E_UNKNOWNGROUP The  parameter is not null but does not specify a recognized command group. /// OLECMDERR_E_NOTSUPPORTED The  parameter is not a valid command in the group identified by . /// OLECMDERR_E_DISABLED The command identified by  is currently disabled and cannot be executed. /// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by , but no help is available. /// OLECMDERR_E_CANCELED The user canceled the execution of the command. [PreserveSig] [return: MarshalAs(UnmanagedType.I4)] int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, [MarshalAs(UnmanagedType.LPArray)] [In] object[] pvaIn, int pvaOut); } } 

axwebbrowser1.Silent = true;

Acabo de encontrar esto:

  private static bool TrySetSuppressScriptErrors(WebBrowser webBrowser, bool value) { FieldInfo field = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { object axIWebBrowser2 = field.GetValue(webBrowser); if (axIWebBrowser2 != null) { axIWebBrowser2.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, axIWebBrowser2, new object[] { value }); return true; } } return false; } 

ejemplo de uso para configurar webBrowser en modo silencioso: TrySetSuppressScriptErrors (webBrowser, true)

Aquí hay una solución alternativa:

 class extendedWebBrowser : WebBrowser { ///  /// Default constructor which will make the browser to ignore all errors ///  public extendedWebBrowser() { this.ScriptErrorsSuppressed = true; FieldInfo field = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { object axIWebBrowser2 = field.GetValue(this); axIWebBrowser2.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, axIWebBrowser2, new object[] { true }); } } }