Tony
Tony

Reputation: 17647

How to interact with DOM on a UWP WebView?

I have a UWP XAML Page and a WebView

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

How to read and manipulate the DOM of the document that was loaded on this WebView?

Upvotes: 1

Views: 1603

Answers (1)

Nico Zhu
Nico Zhu

Reputation: 32775

How to interact with DOM on a UWP WebView?

You can use InvokeScriptAsync with the JavaScript eval function to use the HTML event handlers, and to use window.external.notify from the HTML event handler to notify the application using 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 });
}

Scripts in the web view content can use window.external.notify with a string parameter to send information back to your app. To receive these messages, handle the ScriptNotify event.

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.
}

For more, Please refer to UWP WebView.

Upvotes: 3

Related Questions