How to handle WPF WebBrowser control navigation exception

It's an old question but since I have just suffered through this, I thought I may as well share. First, I implemented Markus' solution but wanted something a bit better as our Firewall remaps 403 message pages.

I found an answer here (amongst other places) that suggests using NavigationService as it has a NavigationFailed event.

In your XAML, add:

<Frame x:Name="frame"/>

In your code-behind's constructor, add:

frame.Navigated += new System.Windows.Navigation.NavigatedEventHandler(frame_Navigated);
frame.NavigationFailed += frame_NavigationFailed;
frame.LoadCompleted += frame_LoadCompleted;

frame.NavigationService.Navigate(new Uri("http://theage.com.au"));

The handlers can now deal with either a failed navigation or a successful one:

void frame_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
{
  e.Handled = true;
  // TODO: Goto an error page.
}

private void frame_Navigated(object sender,  System.Windows.Navigation.NavigationEventArgs e)
{
  System.Diagnostics.Trace.WriteLine(e.WebResponse.Headers);
}

BTW: This is on the .Net 4.5 framework


It is also possible to use dynamic approach here.

wb.Navigated += delegate(object sender, NavigationEventArgs args)
        {
            dynamic doc = ((WebBrowser)sender).Document;
            var url = doc.url as string;
            if (url != null && url.StartsWith("res://ieframe.dll"))
            {
                // Do stuff to handle error navigation
            }
        };

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
            }
        }
    }
}

Tags:

C#

.Net

Wpf