I had a WebBrowser control embedded in my C# application which would bring up the URL page that I needed. Recently I came across a situation where I had to suppress any javascript errors that occurred in this web page.
Previously in the .Net Framework 1.0, I was using the COM version of the WebBrowser and I used the AxWebBrowser. For users who are still using this reference, the suggested way for suppressing the script errors is documented here:
http://support.microsoft.com/?kbid=279535
However, I migrated recently to .Net Framework 2.0 and I now use the System.Windows.Forms.WebBrowser which comes as a part of this framework. This control now has a property namely ScriptErrorsSuppressed which will disable any error dialogs when set to true. A note of caution though: The above property will not only suppress script errors but any errors that originate from the underlying ActiveX control.
If you need control of the error that has occurred and play around with the parameters/error, a better way to do is by using the DocumentCompleted Event.
Here is a sample code of how I implemented:
// Register the event
private void SetBrowserSettings()
{
_webBrowser.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(_webBrowser_DocumentCompleted);
}
// Handle the event
// Invoked after the document has completed loading
void _webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
((System.Windows.Forms.WebBrowser)sender).Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);
}
// Handles any errors that occur after the document has loaded
private void Window_Error(object sender, HtmlElementErrorEventArgs e)
{
MyLog(LogLevel.Error, "Script error occurred at URL {0}, Line Number {1}. Description {2}", e.Url, e.LineNumber, e.Description);
// Ignore the error and suppress the error dialog box.
e.Handled = true;
}
You may also use the Navigated event in a similar fashion. But be aware that if the user hits the refresh button, this event will not be invoked again. So depending on your requirement, you can implement it either way
You can also find further enhancements to the WebBrowser control discussed here:
http://www.codeproject.com/csharp/ExtendedWebBrowser.asp?df=100&forumid=285594&exp=0&fr=26