9

WebView2简单试用(三)—— 新窗口打开页面的处理

 3 years ago
source link: https://www.cnblogs.com/TianFang/p/14353577.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

当我们进行页面跳转的时候,有的时候回使用新窗口打开,WebView2会弹出一个有默认样式的新窗口,而这往往不是我们所想要的效果。

要重载这一行为,实现在自定义的窗口中承载新的web页面,需要我们处理CoreWebView2.NewWindowRequested事件。

    await webView.EnsureCoreWebView2Async();
    webView.CoreWebView2.NewWindowRequested += OnNewWindowRequested;

事件处理方式如下:

    var deferral = e.GetDeferral();
    e.NewWindow = webView.CoreWebView2;
    deferral.Complete();

简单的来说有如下三步:

  1. 获取Deferral对象
  2. 将EventArgs.NewWindow的引用赋为新的CoreWebView控件
  3. 调用Deferral.Coimplete函数

我这里是将新窗口在当前页面中打开,实现类似多tab页的浏览器。则需要新建webview2控件,此时需要注意等待初始化完成,并且新的webview2控件同样要增加NewWindowRequested的处理:

    var deferral = e.GetDeferral();     //需要同步获取,不要异步等待后再获取
    await webView.EnsureCoreWebView2Async();
    e.NewWindow = webView.CoreWebView2;
    deferral.Complete();

参考文档:

Create tabs using WebView2 - Edge


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK