繁体   English   中英

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

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

我已切换到使用 UWP (Windows.UI.Xaml.Controls) 但现在无法检测 webview 选项卡文本何时更改。

文本示例

我以前使用过 OnTitleChanged 事件,但在 UWP 中找不到替代方法。

我可以在 webView 中看到“DocumentTitle”,并且它总是在必要时更新。

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

我已经尝试了 WebView 中的每个内置事件,但在更新时似乎没有一个会触发。

任何人都可以建议和替代方法来触发事件或监视此值吗?

Unfortunately, there is no OnTitleChanged event in UWP WebView, but you could inject eval function into html page as Mehrzad Chehraz said. 请参考以下详细代码。

使 eval function 用于检测标题已更改。

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

调用InvokeScriptAsync方法注入 eval。 (webview导航完成后调用下方)

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

ScriptNotify事件处理程序中更改的侦听值

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

有关更多信息,请查看UWP WebView 教程

我最终使用了什么

    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