我已经切换到使用UWP(Windows.UI.Xaml.Controls(,但现在已经失去了检测Web视图选项卡文本何时更改的能力。
文本示例
我以前使用过OnTitleChanged事件,但在UWP中找不到替代方案。
我可以在webView中看到"DocumentTitle",它总是在必要时更新。
WebView wv_Browser = new WebView();
string Example = wv_Browser.DocumentTitle;
我已经尝试了WebView中的每一个内置事件,但当更新时,似乎没有一个触发。
有人能提出触发事件或监控该值的替代方法吗?
不幸的是,UWP WebView中没有OnTitleChanged
事件,但正如Mehrzad Chehraz所说,您可以将eval函数注入html页面。请参阅以下详细代码。
使用于检测标题的eval函数更改。
string functionString = " new MutationObserver(function () { window.external.notify(document.title); }).observe(document.querySelector('title'), { childList: true })";
调用InvokeScriptAsync
方法来注入eval。(当网络视图导航完成时,请在下面调用(
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 });
}