WebView2 CallDevToolsProtocolMethodAsync 问题与 Fetch.continueRequest

问题描述

我在 .net 5 WPF 应用程序中使用 WebView2,并且一直在使用 devtools 协议作为拦截特定资产请求的手段。查看 Chrome 开发文档 (https://chromedevtools.github.io/devtools-protocol/),可以拦截请求,然后决定是继续、取消还是自己满足。

我已经能够成功拦截一个网络请求(例如 https:// www.somedomain.tld),但我无法成功继续请求(这可能会触发任何其他资产请求作为解析的 html 响应的结果)。

WebView 初始化后,我执行以下操作(有效):

// Intercept requests
var receiver = webView.CoreWebView2.GetDevToolsProtocolEventReceiver("Fetch.requestPaused");
receiver.DevToolsProtocolEventReceived += FetchRequestPaused;
await webView.CoreWebView2.CallDevToolsProtocolMethodAsync("Fetch.enable","{}");

这是我的事件处理程序 - 它没有做我期望的事情(尽管它至少现在没有死锁):

private void FetchRequestPaused(object sender,Microsoft.Web.WebView2.Core.CoreWebView2DevToolsProtocolEventReceivedEventArgs e)
{
   var doc = JsonDocument.Parse(e.ParameterObjectAsJson);
   var id = doc.RootElement.GetProperty("requestId");
   var payload = $"{{\"requestId\":\"{id}.0\"}}";

   // We can't do this as an async call as it will try to post to the main thread,which is
   // busy waiting in this event handler,so we deadlock
   //_ = await webView.CoreWebView2.CallDevToolsProtocolMethodAsync("Fetch.continueRequest",payload);

   // Exception: Value does not fall within the expected range.
   // var result = await webView.CoreWebView2.CallDevToolsProtocolMethodAsync("Fetch.continueRequest",payload).ConfigureAwait(false);

   // PROBLEM: This invokes the call on the UI thread OK...
   Application.Current.dispatcher.Invoke(new Action(() =>
   {
      // ...but it doesn't actually do anything
      webView.CoreWebView2.CallDevToolsProtocolMethodAsync("Fetch.continueRequest",payload);
   }));
}

不仅请求的页面没有完成加载,而且浏览器仍处于异常状态,因此右键单击控件并选择“刷新”会崩溃 - 产生 COMException:

System.Runtime.InteropServices.COMException: 'The group or resource is not in the correct state to perform the requested operation. (0x8007139F)'

谁能看到我在这里做错了什么或遗漏了什么??

谢谢!

其他信息

在将事件替换为已弃用的 Network.setRequestInterception / Network.continueInterceptedRequest 等效项时,我看到了相同的行为 - 这至少告诉我们这要么是我的调用代码有问题(很可能)或者 WebView2(可能)而不是 Chromium 中的错误

有什么想法吗?

解决方法

进一步挖掘后,我意识到有两个问题。首先是我安装的 Edge 版本稍有落后。第二个是我的 Action 委托是同步的。调用应为:

// Somebody forgot some 'async' keywords..!
Application.Current.Dispatcher.Invoke(new Action(async () =>
{
   var x = await webView.CoreWebView2.CallDevToolsProtocolMethodAsync("Fetch.continueRequest",payload);
}));