简体   繁体   中英

UWP Webview - Trigger event when Tab Title changes (DocumentTitle)

I have switched to using UWP (Windows.UI.Xaml.Controls) but now have lost the ability to detect when the webview tab text changes.

Example of text

I previously used an OnTitleChanged event but I cannot find an alternative for this in UWP.

I can see the 'DocumentTitle' in the webView, and it is always updating when necessary.

WebView wv_Browser = new WebView();
string Example = wv_Browser.DocumentTitle;

I have tried every built in event in the WebView but not one of them seem to fire when this updates.

Can anyone suggest and alternative way to trigger an event or monitor this value?

Unfortunately, there is no OnTitleChanged event in UWP WebView, but you could inject eval function into html page as Mehrzad Chehraz said. Please refer the following detail code.

Make eval function for detecting title changed.

string functionString = " new MutationObserver(function () { window.external.notify(document.title); }).observe(document.querySelector('title'), { childList: true })";

Call InvokeScriptAsync method to inject eval. (call below when webview navigation completed)

await MyWebView.InvokeScriptAsync("eval", new string[] { functionString });

listen value changed in ScriptNotify event handler

private void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
    var title = e.Value;
}

For more info please check UWP WebView tutorial .

What I ended up using

    private void CreateWebView()
    {
        WebView webview = new WebView();
        webview .DOMContentLoaded += async (s, e) =>
        {
            WebView_DOMContentLoaded(webview);
        };
        webview .ScriptNotify += (s, e) => {
             . . . Do whatever
        };
    }

   private async void WebView_DOMContentLoaded(WebView sender)
    {
        string function = @"new MutationObserver(function(mutations){window.external.notify(document.getElementById('pageTitle').innerHTML)}).observe(document.getElementById('pageTitle'),{attributes:true,childList:true,subtree:true});";
        await sender.InvokeScriptAsync("eval", new string[] { function });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM