2

我究竟做错了什么?

我使用 w3schools.com 进行测试。

webView.Navigate(new Uri("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert"));

Package.appxmanifest 文件

在此处输入图像描述

导航完成

private async void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    string result = await sender.InvokeScriptAsync("eval", new string[] { "window.alert = function (AlertMessage) {window.external.notify(AlertMessage)}" });
}

脚本通知

private async void WebView_ScriptNotify(object sender, NotifyEventArgs e)
{
     MessageDialog dialog = new MessageDialog(e.Value);
     await dialog.ShowAsync();
}
4

1 回答 1

1

这里的问题与您用于测试的网页(https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert )有关。

如果您在此页面上进行检查,您会发现“Try it”按钮实际上位于iframe名为“iframeResult”的位置。

<iframe frameborder="0" id="iframeResult" name="iframeResult">
  <!DOCTYPE html>
  <html>
    <head></head>
    <body contenteditable="false">
      <p>Click the button to display an alert box.</p>
      <button onclick="myFunction()">Try it</button>
      <script>
          function myFunction() {
              alert("Hello! I am an alert box!");
          }
      </script>
    </body>
  </html>
</iframe>

因此,当您覆盖父框架window.alert中的方法时,单击“尝试”时您的代码将不起作用。alert为了使您的代码正常工作,您只需将其更改为iframeResult.window.alert如下所示:

private async void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    string result = await sender.InvokeScriptAsync("eval", new string[] { "iframeResult.window.alert = function(AlertMessage) {window.external.notify(AlertMessage)}" });
}
于 2017-02-25T11:27:09.267 回答