How can I prevent a WebView control from opening a browser window?

Raymond Chen

Raymond

A customer had an application that used a UWP WebView control. Some Web sites open links in a new window by using techniques like TARGET=_blank. When the user clicks on such a link, it opens in a Web browser. The customer wanted to know how to prevent this.

To do this, you can handle the New­Window­Requested event. You can mark the event as Handled, in which case the system will consider the action complete and will not send the request to the user’s default Web browser.

<!-- XAML -->
<WebView NewWindowRequested="OnNewWindowRequested" />

// C# code-behind
void OnNewWindowRequested(WebView sender, WebViewNewWindowRequestedEventArgs e) 
{ 
    // Block all requests to open a new window
    e.Handled = true; 
} 

You can inspect the Referrer and Uri properties to learn more about what triggered the new window.

  • Referrer is the page that wants to open the window.
  • Uri is the page that it wants to open.

If your handler is a coroutine, then you must set Handled = true before performing any await operations, because the handler returns to its caller as soon as you perform an await, and the rest of the handler runs as an asynchronous task.

Raymond Chen
Raymond Chen

Follow Raymond   

0 comments

Comments are closed.