January 2nd, 2019

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

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.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.