Search code examples
c#webviewuwpwebbrowser-controlinvokescript

How to get any web site alert message UWP WebView


what am I doing wrong?

I used w3schools.com for testing.

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

Package.appxmanifest file

enter image description here

NavigationCompleted

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)}" });
}

ScriptNotify

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

Solution

  • The problem here is related to the web page (https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert) you are using to test.

    If you inspect on this page, you will find the "Try it" button is actually in a iframe named "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>

    So your code won't work while clicking "Try it" as you are overriding window.alert which is the alert method in parent frame. And to make your code work, you can simply change it to iframeResult.window.alert like the following:

    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)}" });
    }