无法 运行 带有 WebView Universal Windows App 的简单脚本

Cannot run simple script with WebView Universal Windows App

我将简单的 html 文件(保存在项目中)加载到 WebView。加载成功显示"Hello World" header.

文件index.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>ABC</title>
<script>
    function SayHello() {
        return "hello";
    };
</script>
</head>
<body>
    <h1>Hello World</h1>
</body>
</html>

加载到 WebView

 protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            webView.Navigate(new Uri("ms-appx-web:///index.html", UriKind.RelativeOrAbsolute));

// Exception below line
            var data = await webView.InvokeScriptAsync("eval", new List<string> { "SayHello();" });
            Debug.WriteLine(data);
        }

我不明白为什么会这样。它在 Google Chrome 上成功 运行。我错过了什么吗?

关于Navigate方法的MSDN:

Loads the HTML content at the specified Uniform Resource Identifier (URI).

当您调用该方法时,它不会立即加载内容,可能需要一些时间。您需要监听 DOMContentLoaded 事件,然后 运行 页面实际加载到 WebView 时的脚本。

webView1.DOMContentLoaded += webView1_DOMContentLoaded;
...
...
private async void webView1_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
{
   var data = await webView.InvokeScriptAsync("eval", new List<string> { "SayHello();" });
   Debug.WriteLine(data);
}

我认为您应该转到 URI 中的清单配置文件, Windows 运行时访问=全部 类型 = 包括