首页 > 解决方案 > 带有 JavaScript 文件的 HTML 在 WPF 应用程序内的 WebView2 上不起作用

问题描述

在我的WPF项目中,我使用的 WebView2控件可以按预期正确显示常规 html 文件和/或 html 字符串。但是,如果 html 字符串包含以JavaScript文件为源的脚本标记,则链接的 JavaScript 文件中的代码不起作用。但是,如果我将生成的完全相同的 HTML 字符串复制到驱动器上的本地文件并将其另存为 HTML 文件,则相同的 HTML 以及链接的 JavaScript 可以正常工作:

备注:代码中的文件来自官方 JQuery 下载站点JQueryTest.js的第二个链接。由于文件很大,为简洁起见,我没有在此处包含其代码。但是,如果您愿意,可以从链接下载文件进行测试。Download the uncompressed, development jQuery 3.6.0

问题:我们怎样才能使JavaScript下面的代码工作。我阅读了以下官方文档,但无法弄清楚如何在这里实现。

MainWindow.xaml

<Window x:Class="WpfJunkWebView2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfJunkWebView2"
        xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button x:Name="btnTest" Content="Test" Click="btnTest_Click" HorizontalAlignment="Left"/>
        <wv2:WebView2 x:Name="wvTest" Grid.Row="1"/>
    </Grid>
</Window>

MainWindow.xaml.cs

private async void btnTest_Click(object sender, RoutedEventArgs e)
{
    string sFilePath = System.IO.Path.Combine(Environment.CurrentDirectory, @"JQueryTest.js");
    Uri uri = new Uri(sFilePath);
    string uriPath = uri.AbsoluteUri;

    string sHtml = "<!DOCTYPE html>" +
    "<html>" +
    "<head>" +
        "<script src=\"" + uriPath + "\"></script>" +
        "<script>" +
            "$(document).ready(function(){" +
            "$(\"p\").click(function(){" +
            "$(this).hide();" +
                "});" +
            "});" +
        "</script>" +
    "</head>" +
    "<body>" +
        "<p> If you click on this line, it will disappear.</p>" +
        "<p> Click this text away!</p>" +
        "<p> Click text too!</p>" +
    "</body>" +
    "</html>";

    System.Diagnostics.Debug.Write(sHtml); //you can copy this HTML into an HTML file to test that it works.
    await wvTest.EnsureCoreWebView2Async();
    wvTest.NavigateToString(sHtml); //this line successfully displays HTML inside WebView2 but the JavaScipt code does not work
}

以上代码生成的HTML如下

<!DOCTYPE html>
<!-- saved from url=(0011)about:blank -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script src="file:///C:/tmp/WpfJunkWebView2/bin/Debug/netcoreapp3.1/JQueryTest.js"></script><script>$(document).ready(function(){$("p").click(function(){$(this).hide();});});</script></head><body><p> If you click on this line, it will disappear.</p><p> Click this text away!</p><p> Click text too!</p></body></html>

可以通过VSCode格式化上面的 html :将上面的 html 字符串复制到一个新的 HTML 文件中VSCode,右键单击Format Document得到以下内容。然后可以打开这个 HTML 文件来测试上述场景,以验证它在没有 Webview2 的情况下是否有效:

<!DOCTYPE html>
<!-- saved from url=(0011)about:blank -->
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="file:///C:/tmp/WpfJunkWebView2/bin/Debug/netcoreapp3.1/JQueryTest.js"></script>
    <script>
        $(document).ready(function(){
            $("p").click(function(){
                $(this).hide();
                });
                });
    </script>
</head>

<body>
    <p> If you click on this line, it will disappear.</p>
    <p> Click this text away!</p>
    <p> Click text too!</p>
</body>

</html>

MainWindow 显示屏幕截图

当您运行应用程序并单击该行中的三行中的任何一行时,MainWindow该行应该消失 - 但它没有发生。但是,如果将生成的 html 手动保存到文件中.html,然后在浏览器中手动打开(我在 MS Edge 和 Google Chrome 上对其进行了测试),则此功能可以正常工作。

在此处输入图像描述

标签: javascriptc#jquerywpfwebview2

解决方案


当您尝试失败的 WebView2 场景时,您可以打开 DevTools 并检查控制台吗?我猜问题是您的 NavigateToString 内容不允许访问文件 URI。如果是这样,您可以将 HTML 写入文件并导航到文件 URI 而不是使用 NavigateToString,或者您可以尝试使用CoreWebView2.SetVirtualHostNameToFolderMapping通过 HTTP URI 而不是文件 URI 托管 JavaScript 文件。


推荐阅读