Beyto A.
Beyto A.

Reputation: 164

WebView ContentChanged Event

There is a website which I want to use in my application to display content from it.

I have to run a JavaScript code like getNames() which will fill the div with names in it. After executing the code, it takes 1-2 seconds to fill in.

I want to update the app when the div is filled. Problem is, I couldn't find an event like webView1.ContentChanged or webView1.SourceChanged. Only way to do this seems like creating a Timer, setting it to 3 seconds, and start it when the getNames() is executed and then getting the source code.

Anyone have any idea?

Thanks

Upvotes: 3

Views: 2741

Answers (1)

Xie Steven
Xie Steven

Reputation: 8591

WebView has no built-in event to support detecting the content changed. You could use InvokeScriptAsync with the JavaScript eval function to use the HTML event handlers, and to use window.external.notify from the HTML event handler to notify the application using WebView.ScriptNotify.

About how to detect html content changed by javascript, you could refer to DOM mutation events replacement

MDN->Web technology for developers->Web APIs->MutationObserver

I've made a simple code sample for you:

<WebView Source="ms-appx-web:///HTMLPage1.html" ScriptNotify="WebView_ScriptNotify"></WebView>

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript">

        function detectContent()
        {
            var target = document.getElementById('div');

            var observer = new MutationObserver(function (mutations) {
                mutations.forEach(function (mutation) {
                    window.external.notify('div changed');
                    update("div changed");
                });
            });
            var config = { attributes: true, childList: true, characterData: true };
            observer.observe(target, config);
        }

        function update(e)
        {
            var div = document.getElementById("div");
            div.innerHTML = e;
        }
    </script>
</head>
<body onload="detectContent();">
    <div id="div" style="margin-top:100px;"></div>
    <br />
    <input value="update" onclick="update('abc');" type="button"/>
</body>
</html>

private void WebView_ScriptNotify(object sender, NotifyEventArgs e)
{
    System.Diagnostics.Debug.WriteLine(e.Value);
}

Then if the Div's content is changed, the WebView's ScriptNotify event will be fired. In my code sample, Webview just load the local html page.

In your case, if the website isn't owned by you, you would need to use InvokeScriptAsync to inject javascript code in WebView navigatstarting event.

Upvotes: 2

Related Questions