在 WebView UWP 中调用 Javascript

Invoke Javascript inside WebView UWP

我想将以下内容添加到我的 webview

    <html>
<body>
<h1>My First Heading</h1>
 <div id="mydiv" style="width: 100%; height: 100%;" ></div> 
    <script src="https://mydomain/Embed.js" type="text/Javascript">
        </script>
</body>
</html>

我的代码是这样的

 <WebView x:Name="wView"></WebView>

代码隐藏

wView.NavigateToString(
            @"<html> <body> <h1>My First Heading</h1> <div id=""mydiv"" style=""width: 100%; height: 100%;"" ></div> <script src=""https://mydomain/Embed.js"" type=""text/Javascript""> </script> </body> </html>");

使用这种方法,我无法在 Embed.js 中 运行 任何 javascript。仅显示 H1 标签内的内容。我怎样才能确保 webview 中的 javascript(在我的例子中是 Embed.js)被执行?

根据WebView.NavigateToString()的描述:

NavigateToString supports content with references to external files such as CSS, scripts, images, and fonts. However, it does not provide a way to generate or provide these resources programmatically.

因此,让js有效的更好的方法是在项目中创建一个HTML文件,将你的HTML内容写入其中,并在下面的方法中使用:

wView.Source = new Uri("ms-appx-web:///Html/myHtmlFile.html");

更新

如果需要动态修改HTML文件的内容,那么ms-appx-web就不合适了,因为它是针对包中的文件,而包中的文件不能直接在运行时修改。

根据this document。您可以将 html 文本保存在 LocalFolder 的子文件夹中作为临时文件,并通过 ms-appdata:

引导它
var htmlFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("html", CreationCollisionOption.OpenIfExists);
var localFile = await htmlFolder.CreateFileAsync("temp.html", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(localFile, html);
wView.Navigate(new Uri("ms-appdata:///local/html/temp.html"));

P.S。临时文件必须存放在LocalFolder的子文件夹中,不能有同级链接