【问题标题】:How to get any web site alert message UWP WebView如何获取任何网站警报消息 UWP WebView
【发布时间】:2024-01-08 18:22:01
【问题描述】:

我做错了什么?

我使用 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();
}

【问题讨论】:

标签: c# webview uwp webbrowser-control invokescript


【解决方案1】:

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

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

<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>

因此,当您覆盖父框架中的 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)}" });
}

【讨论】:

  • 这不适用于来自任何其他网站的 iframe,因为 id iframeResult 特定于 w3schools。