如何在 WebView2 中获取对新 window 的引用?

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

说,我正在点击 Flashscore 网站上的一些网球比赛。弹出一个新的 window。我想在 WebView2:

中捕获第二个 window
browser.CoreWebView2Ready += delegate
{ 
    browser.CoreWebView2.NewWindowRequested += OnNewWindowRequested;
};

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

然而,newWindownull。同时,使用WindowFeatures,我可以得到新的window的高度或宽度:

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

如何捕获对第二个 window 的引用?

NewWindowRequested 事件可以让您取消打开一个新的 window 或用您自己的替换 window,但是您不能让 WebView2 为您打开一个新的 window 并获得一个引用那个新的 window.

NewWindowRequested 事件场景:

  1. 在事件处理程序中不采取任何操作或不订阅。 WebView2 将打开一个新的 window,其中最小 UI 不受最终开发人员的控制。
  2. 将事件参数的 Handled 属性 设置为 true。取消打开新 window。如果 window.open 是创建新 window 的内容,则 return 值是 null.
  3. 将事件参数上的 Handled 属性 设置为 true,并使用 Uri 属性 在用户的默认浏览器中打开 URI或以其他方式处理 WebView2 之外的新 window。
  4. 将事件参数上的 Handled 属性 设置为 true,并将 NewWindow 属性 设置为您创建的新 CoreWebView2。如果 window.open 是创建新 window 的对象,则 return 值是与您提供的 CoreWebView2 相对应的新 window 对象。您可以通过 creating one from a CoreWebView2Environment class 获取新的 CoreWebView2,或者如果您在 WPF、WinForms 或 WinUI 中使用 WebView2 元素,则可以创建新的 WebView2 元素并使用其 CoreWebView2 属性 .

您可以看到一些使用 the NewWindowRequested event in our sample app 的例子。