如何在 UWP Web View 上与 DOM 交互



我有一个UWP XAML页面和一个WebView

<WebView Name="webview1" Margin="10"
             Source="http://www.apelosurgentes.com.br/en-us/" 
             LoadCompleted="WebView_LoadCompleted" />

如何读取和操作在此 Web 视图上加载的文档的 DOM?

如何在 UWP Web View 上与 DOM 交互?

您可以将InvokeScriptAsync与 JavaScript eval 函数一起使用以使用 HTML 事件处理程序,并使用 HTML 事件处理程序中的 window.external.notify 来使用 WebView.ScriptNotify 通知应用程序。

private async void Button_Click(object sender, RoutedEventArgs e)
{
    string functionString = String.Format("document.getElementById('nameDiv').innerText = 'Hello, {0}';", nameTextBox.Text);
    await webView1.InvokeScriptAsync("eval", new string[] { functionString });
}

Web 视图内容中的脚本可以使用带有字符串参数的 window.external.notify 将信息发送回应用。若要接收这些消息,请处理 ScriptNotify 事件。

public MyPage()
{
    this.InitializeComponent();
    MyWebView.ScriptNotify += MyWebView_ScriptNotify;
    // Here we have to set the AllowedScriptNotifyUri property because we are 
    // navigating to some site where we don't own the content and we want to 
    // allow window.external.notify() to pass data back to the app.
    List<Uri> allowedUris = new List<Uri>();
    allowedUris.Add(new Uri("http://www.bing.com"));
    MyWebView.AllowedScriptNotifyUris = allowedUris;
}
void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
    // Respond to the script notification.
}

有关详细信息,请参阅 UWP WebView

最新更新