WebView2 (WPF) - 从本地文件夹加载网站并调用 C# 函数和调用 JS 函数

adm*_*min 3 javascript c# wpf function webview2

我正在使用 WebView2 制作 WPF 应用程序。

\n

将有一个安装程序将 WPF 应用程序安装在文件夹中,还将下载网站并将其写入安装目录的子文件夹中。比如这样:

\n
Installation Directory\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80Website\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80index.css\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80index.html\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80WPF Self Contained EXE\n
Run Code Online (Sandbox Code Playgroud)\n

WebView2 将使用此加载网站(我认为):webView.CoreWebView2.Navigate(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Website");

\n

这应该加载index.html及其引用的所有文件,例如index.css.

\n

现在我主要关心的是如何从 C# 调用 JavaScript 函数。到目前为止,在谷歌搜索后我只找到了 WebView1 的方法。我找不到任何有关从 JavaScript 调用 C# 方法的信息。

\n

所以三件事:

\n
    \n
  1. webView.CoreWebView2.Navigate(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Website");从本地文件夹加载网站是否正确?
  2. \n
  3. 我如何调用 JavaScript 函数并从 C# 方法将 C# 对象传递给它。
  4. \n
  5. 如何从 JavaScript 脚本调用 C# 函数?
  6. \n
\n

这可能吗?

\n

谢谢。

\n

Dav*_*ney 6

使用文件 URI

我不确定 AppDomain.CurrentDomain.BaseDirectory 是否总能为您提供正确的路径。您可以使用类似以下内容:

string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string exeFolder = System.IO.Path.GetDirectoryName(exePath);
string websiteFolder = Path.Combine(exeFolder, "website");
string htmlPath = Path.Combine(websiteFolder, "index.html");

webView.CoreWebView2.Navigate(htmlPath);
Run Code Online (Sandbox Code Playgroud)

您必须包含index.html 本身的路径,而不仅仅是包含index.html 的文件夹。

通常,Navigate 应采用 URI,但如果您提供 Windows 文件路径,它会将其转换为文件 URI,并且应该可以工作。

当尝试合并 http(s) URI 和其他需要 https 的 Web 平台功能时,文件 URI 有一些限制。

使用虚拟 HTTPS URI

如果您在使用文件 URI 时遇到问题,可以使用CoreWebView2.SetVirtualHostNameToFolderMapping将 Windows 文件路径映射到虚假的 HTTPS 主机名:

string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string exeFolder = System.IO.Path.GetDirectoryName(exePath);
string websiteFolder = Path.Combine(exeFolder, "website");

webView.CoreWebView2.SetVirtualHostNameToFolderMapping("appassets.example", websiteFolder, CoreWebView2HostResourceAccessKind.DenyCors);
webView.CoreWebView2.Navigate("https://appassets.example/index.html");
Run Code Online (Sandbox Code Playgroud)

这将创建一个假主机名“appassets.example”,该主机名将映射到您的 Windows 文件路径。由于它是 HTTPS URI,因此您不会遇到与文件 URI 相同的问题。

脚本中的宿主对象

对于问题 2 和 3,您可以使用CoreWebView2.AddHostObjectToScript。AddHostObjectToScript 的当前实现要求对 C# 类进行特殊标记。您可以在 AddHostObjectToScript 文档中看到它。