HelloWindowsPhone
HelloWindowsPhone

Reputation: 700

Cannot run simple script with WebView Universal Windows App

I have simple html file (save in project) load on to WebView. It load success and display "Hello World" header.

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

Load to 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);
        }

I don't understand why this happen. It success run on Google Chrome. Am I miss something here?

Upvotes: 0

Views: 90

Answers (2)

Mehrzad Chehraz
Mehrzad Chehraz

Reputation: 5137

MSDN about Navigate method:

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

When you call the method, it doesn't instantly load the content, it may take some time. You need to listen to the DOMContentLoaded event and then run the script when page is actually loaded into the 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);
}

Upvotes: 3

Eng Soon Cheah
Eng Soon Cheah

Reputation: 257

I think you should go to Manifest profile in URI, Windows Runtime Access= All Type = Include

enter image description here

Upvotes: -1

Related Questions