【问题标题】:UWP Webview - Trigger event when Tab Title changes (DocumentTitle)UWP Webview - 选项卡标题更改时触发事件(DocumentTitle)
【发布时间】:2020-08-10 05:48:43
【问题描述】:

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

Example of text

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

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

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

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

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

【问题讨论】:

  • 您应该使用 InvokeScriptAsync 在文档上运行 JavaScript 代码并接收到标题更改事件,然后通过将对象注入 JavaScript 代码将事件发送回您的应用程序。
  • 感谢您的帮助。我最终还需要创建事件并注入它,但在查看了你所说的内容后它就可以工作了。

标签: c# xaml webview uwp


【解决方案1】:

不幸的是,UWP WebView 中没有OnTitleChanged 事件,但您可以像 Mehrzad Chehraz 所说的那样将 eval 函数注入到 html 页面中。请参考以下详细代码。

制作用于检测标题更改的评估函数。

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 tutorial

【讨论】:

  • 谢谢,我最终得出了相同的结论,实际上几乎完全相同的代码。感谢加载“新的 MutationObserver(function(mutations){window.external.notify(document.getElementById('pageTitle').innerHTML)}).observe(document.getElementById('pageTitle'),{attributes:true,childList:真,子树:真});"
【解决方案2】:

我最终使用了什么

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 2011-05-04
    • 2014-07-21
    相关资源
    最近更新 更多