C# – How to handle WPF WebBrowser control navigation exception

cnetwpf

Let's say that WPF WebBrowser control shows some navigation errors and the page is not showing.

So there is an exception of WPF WebBrowser control.

I found some similar questions here but it is not what I need.

In fact, I need some method and object that has an exception to get it somehow.

How do we can handle it?

Thank you!

P.S. There is some approach for WinForm WebBrowser Control… Can we do something similar to WPF WebBrowser control?

public Form13()
{
     InitializeComponent();

     this.webBrowser1.Navigate("http://blablablabla.bla");

      SHDocVw.WebBrowser axBrowser = (SHDocVw.WebBrowser)this.webBrowser1.ActiveXInstance;
      axBrowser.NavigateError +=
           new SHDocVw.DWebBrowserEvents2_NavigateErrorEventHandler(axBrowser_NavigateError);
}

void axBrowser_NavigateError(object pDisp, ref object URL,
       ref object Frame, ref object StatusCode, ref bool Cancel)
{
     if (StatusCode.ToString() == "404")
     {
         MessageBox.Show("Page no found");
     }
}

P.S. #2 To host WinForm WebBrowser control under WPF App is not an answer I think.

Best Answer

I'm struggling with a similar problem. When the computer loses internet connection we want to handle that in a nice way.

In the lack of a better solution, I hooked up the Navigated event of the WebBrowser and look at the URL for the document. If it is res://ieframe.dll I'm pretty confident that some error has occurred.

Maybe it is possible to look at the document and see if a server returned 404.

private void Navigated(object sender, NavigationEventArgs navigationEventArgs)
{
    var browser = sender as WebBrowser;
    if(browser != null)
    {
        var doc = AssociatedObject.Document as HTMLDocument;
        if (doc != null)
        {
            if (doc.url.StartsWith("res://ieframe.dll"))
            {
                // Do stuff to handle error navigation
            }
        }
    }
}
Related Topic