WPF WebBrowser control - how to suppress script errors?
I found a similar question here:
How do I suppress script errors when using the WPF WebBrowser control?
But non of those solutions work for me. I need to stop the popups from appearing as i am using the WebBrowser to automate admin tasks on a website.
SuppressScriptErrors
does not appear to be an available attribute on my WebControl :(
Solution 1:
Here is a C# routine that is capable of putting WPF's WebBrowser
in silent mode. You can't call it at WebBrowser initialization as it 's too early, but instead after navigation occured. Here is a WPF sample app with a wbMain WebBrowser component:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
wbMain.Navigated += new NavigatedEventHandler(wbMain_Navigated);
}
void wbMain_Navigated(object sender, NavigationEventArgs e)
{
SetSilent(wbMain, true); // make it silent
}
private void button1_Click(object sender, RoutedEventArgs e)
{
wbMain.Navigate(new Uri("... some url..."));
}
}
public static void SetSilent(WebBrowser browser, bool silent)
{
if (browser == null)
throw new ArgumentNullException("browser");
// get an IWebBrowser2 from the document
IOleServiceProvider sp = browser.Document as IOleServiceProvider;
if (sp != null)
{
Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E");
object webBrowser;
sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out webBrowser);
if (webBrowser != null)
{
webBrowser.GetType().InvokeMember("Silent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.PutDispProperty, null, webBrowser, new object[] { silent });
}
}
}
[ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IOleServiceProvider
{
[PreserveSig]
int QueryService([In] ref Guid guidService, [In] ref Guid riid, [MarshalAs(UnmanagedType.IDispatch)] out object ppvObject);
}
Solution 2:
Thought it'd be relevant to add here. There is another option to get to the WPF WebBrowser's underlying WebBorwser ActiveX Control and its otherwise inaccessible methods and events. I just discovered it a few days ago. It's very simple and doesn't require initial navigation on WB:
dynamic activeX = this.WB.GetType().InvokeMember("ActiveXInstance",
BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
null, this.WB, new object[] { });
activeX.Silent = true;
Of course, there's a chance this method may not work in future version of the Framework, but so is true about any other undocumented method. So far, it's been there since .NET 3.0. More details with a working code sample here.