简体   繁体   English

UWP Webview - 选项卡标题更改时触发事件 (DocumentTitle)

[英]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.我已切换到使用 UWP (Windows.UI.Xaml.Controls) 但现在无法检测 webview 选项卡文本何时更改。

Example of text文本示例

I previously used an OnTitleChanged event but I cannot find an alternative for this in UWP.我以前使用过 OnTitleChanged 事件,但在 UWP 中找不到替代方法。

I can see the 'DocumentTitle' in the webView, and it is always updating when necessary.我可以在 webView 中看到“DocumentTitle”,并且它总是在必要时更新。

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.我已经尝试了 WebView 中的每个内置事件,但在更新时似乎没有一个会触发。

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. 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.使 eval function 用于检测标题已更改。

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

Call InvokeScriptAsync method to inject eval.调用InvokeScriptAsync方法注入 eval。 (call below when webview navigation completed) (webview导航完成后调用下方)

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

listen value changed in ScriptNotify event handler ScriptNotify事件处理程序中更改的侦听值

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

For more info please check UWP WebView tutorial .有关更多信息,请查看UWP WebView 教程

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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