Change the Uri in WebBrowser.Navigating
-
27-10-2019 - |
Question
Is it possible in the handler of the Navigating event to change the Uri to which the WebBrowser control is navigating ?
The Uri in the event arguments can not be changed, because it is read only, however, I tried to Cancel the navigation and send the browser to a new address with the Navigate method like this:
// I can not do this.
// e.Uri = new Uri( "http://newUri" );
e.Cancel = true;
( (WebBrowser)sender ).Navigate( new Uri( "http://newUri" ) );
however, this makes my application crash without any exception whatsoever.
Does anybody know a solution to this problem?
Solution 2
It turned out that this is an emulator bug. My approach makes the app running on the emulator crash, but it works properly on a real device.
OTHER TIPS
My guess is that you are causing a stack overflow. Each time the navigation event fires, you tell the browser to navigate again, which raises the event again ...
Try adding a boolean to stop your code recursing ...
private bool isRedirecting = false;
private void WebBrowser_OnNavigate(object sender, EventArgs e)
{
if (isRedirecting)
return;
e.Cancel = true;
isRedirecting = true;
( (WebBrowser)sender ).Navigate( new Uri( "http://newUri" ) );
isRedirecting = false;
}