11

WebView2简单试用(九)—— Dev Protocol

 3 years ago
source link: https://www.cnblogs.com/TianFang/p/14405896.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.

有的时候,我们需要实现一些更为高级的操作,以提供更个性化的功能。常用的注入JavaScript的方式已经不能满足我们的要求,此时可以使用Chromium提供的更为高级的API——Chrome Dev Protocol

关于Dev Protocol,我之前写过几篇文章介绍过:

简单的来讲,通过F12调出的DevTool里能实现的功能它都能实现,网上也有大量的文章介绍它,我这里就不重复介绍了。本文这里只是介绍下WebView2中使用DevProtocol的方式。

在WebView2中,我们可以和前面的文章中介绍的一样,通过--remote-debugging-port参数开放调试端口,用websocket的方式来驱动。

    var env = await CoreWebView2Environment
                  .CreateAsync(options:new CoreWebView2EnvironmentOptions(
                                "--remote-debugging-port=9222"));
    await webView.EnsureCoreWebView2Async(env);

除此之外,WebView2也提供了无需通过WebSocket作为中介,直接访问的方法:

  • CoreWebView2.CallDevToolsProtocolMethodAsync
  • CoreWebView2.GetDevToolsProtocolEventReceiver

 基本上从名称中就可以看出使用方法,执行命令和注册回调。一个简单的示例如下:

    await webView.CoreWebView2.CallDevToolsProtocolMethodAsync("Network.enable", "{}");
    var eventRecieiver = webView.CoreWebView2.GetDevToolsProtocolEventReceiver("Network.requestWillBeSent");
    eventRecieiver.DevToolsProtocolEventReceived += (s, e) =>
    {
        Console.WriteLine(e.ParameterObjectAsJson + "\n");
    };

示例进行了两步操作:1. 执行命令Network.enable,启用Network事件回调,2. 注册Network.requestWillBeSent回调,命令执行完后,再访问任何页面时,即可获取当前发送的所有请求信息:

12132-20210216004147402-46358920.png


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK