JohnyL
JohnyL

Reputation: 7142

How do I get reference to the new window in WebView2?

Say, I am clicking on some tennis match on Flashscore web site. A new window pops up. I want to capture that second window in WebView2:

browser.CoreWebView2Ready += delegate
{ 
    browser.CoreWebView2.NewWindowRequested += OnNewWindowRequested;
};

private async void OnNewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e)
{
    var newWindow = e.NewWindow; //null
}

However, newWindow is null. At the same time, using WindowFeatures, I can get height or width of the new window:

uint height = e.WindowFeatures.Height;
uint width = e.WindowFeatures.Width;

How can I capture the reference to the second window?

Upvotes: 2

Views: 6340

Answers (1)

David Risney
David Risney

Reputation: 4377

The NewWindowRequested event can let you cancel opening a new window or replace the window with your own, but you cannot have WebView2 open a new window for you and get a reference to that new window.

NewWindowRequested event scenarios:

  1. Take no action in the event handler or don't subscribe. WebView2 will open a new window with minimal UI that is out of control of the end developer.
  2. Set the Handled property on the event args to true. Cancels opening of the new window. If window.open is what was creating the new window, then the return value is null.
  3. Set the Handled property on the event args to true, and use the Uri property to open the URI in the user's default browser or otherwise handle the new window outside of WebView2.
  4. Set the Handled property on the event args to true, and set the NewWindow property to a new CoreWebView2 that you create. If window.open is what was creating the new window, then the return value is a new window object corresponding to the CoreWebView2 that you provided. You can obtain a new CoreWebView2 by creating one from a CoreWebView2Environment class or if you're using a WebView2 element in WPF, WinForms, or WinUI, you can create a new WebView2 element and use its CoreWebView2 property.

You can see some example of using the NewWindowRequested event in our sample app.

Upvotes: 8

Related Questions