首页 > 解决方案 > 如何从 WebView2 中的 ExecuteScript 获取同步返回

问题描述

只是从这里尝试 Winforms WebView2:https ://github.com/michael-russin/webview2-control

试图弄清楚如何同步使用ExecuteScript 。以任何方式阻塞线程都会阻止脚本运行。

Friend Function ExecuteSync(Script As String) As String
    ExecuteScript(Script, Sub(e) ExecuteSync = e.ResultAsJson)
End Function

感谢您提供任何帮助,因为我找不到任何有关如何执行此操作的示例。

标签: .netwinformswebview

解决方案


不知道 Michael 的 webview2 包装器版本,但如果你使用官方的 Microsoft One:

https://docs.microsoft.com/en-us/microsoft-edge/webview2/webview2-api-reference

它与 Michael 的版本有很多相同的方法和属性名称。

然后,您只需使用可以在主机对象数组中找到的同步对象,使用以下代码即可从 JavaScript 代码中获取对您实现的任何对象的同步调用:

var mynum = chrome.webview.hostObjects.sample.myMethod().sync();

在 C# 中(对不起,我不知道 VB 的等价物)你可以​​在一个类中实现“myMethod”,如下所示:

using Microsoft.Web.WebView2.Core;
using System.Runtime.InteropServices;

namespace EdgeWebView2Test.MyClasses
{
  [ClassInterface(ClassInterfaceType.AutoDual)]
  [ComVisible(true)]
  public class MyJavaScriptApiClass
  {
    public int MyMethod()
    {
      return 10;
    }
  }
}

推荐阅读