The System.Windows.Forms.WebBrowser control has quite a few properties readily available you that aren’t available in it’s big brother – the System.Windows.Controls.WebBrowser. One of them is the ScriptErrorsSupressed property. It’s the property that instructs the web browser control to hide or show an error message box when there are script errors (ex. unhandled javascript errors) on web pages it loads.
If you have a WPF application that needs a web browser control that can suppresses script errors you have two options. One is to use the System.Windows.Forms.WebBrowser bundled inside a WindowsFormsHost or you can use the WPF web browser - System.Windows.Controls.WebBrowser – and use reflection to suppress script errors. Here is the code to do that:
/// <summary>
/// Supress Script Errors
/// </summary>
/// <param name="wb"></param>
/// <param name="Hide"></param>
public void SuppressScriptErrors(System.Windows.Controls.WebBrowser wb, bool Hide)
{
FieldInfo fi = typeof(System.Windows.Controls.WebBrowser).GetField(
"_axIWebBrowser2",
BindingFlags.Instance | BindingFlags.NonPublic);
if (fi != null)
{
object browser = fi.GetValue(wb);
if (browser != null)
{
browser.GetType().InvokeMember("Silent", BindingFlags.SetProperty,
null,browser, new object[] { Hide });
}
}
}
What we’ve done above is set the “Silent” property on the “_axIWebBrowser2” field of the browser using reflection.
Then, you’ll simply need to call it in your WebBrowser control’s Navigated event:
void _webBrowser_Navigated(object sender,
System.Windows.Navigation.NavigationEventArgs e)
{
SuppressScriptErrors( _webBrowser,true);
}
That’s it! What other properties can you find that can be set on the web browser control through reflection? If you find any good ones, leave a comment below!
Tags: wpf
Permalink |