65.9K
CodeProject is changing. Read more.
Home

Navigate a Silverlight WebBrowser to a URL with a Hash (Fragment Identifier)

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Sep 24, 2011

CPOL
viewsIcon

14730

The Silverlight WebBrowser won't navigate to some URL's, but this can be worked around.

If you try to set the Silverlight WebBrowser control to navigate to http://translate.google.com/#en|fr| either via the Source property in the XAML or by using the Navigate function, you will be presented with an exception (strangely, the Windows Forms WebBrowser has no problem with this URL). It seems the Uri class doesn't like to construct URLs that contain a pipe character in the hash (aka, fragment identifier) of the URL (the part of the URL that comes after the "#"). Here is the workaround:
string html = string.Format(
  @"<html><body><script type='text/javascript'>window.location = '{0}';</script></body></html>",
  "http://translate.google.com/#en|fr|");
myWebBrowser.NavigateToString(html);
All you have to do is navigate to some HTML that has JavaScript that navigates to the URL you want the WebBrowser to visit. Here's the VB.NET version:
Dim html As String = String.Format(
  "<html><body><script type='text/javascript'>window.location = '{0}';</script></body></html>",
  "http://translate.google.com/#en|fr|")
myWebBrowser.NavigateToString(html)
I suspect this is either a .NET bug in the implementation of Uri or pipe characters may not strictly be allowed in fragment identifiers. Whatever the reason, this is the workaround (though if somebody else has a more elegant solution, I would love to see it).