Tony
Tony

Reputation: 17637

How to access and manipulate the DOM and JavaScript of WebView?

I have a WebView that I navigate to a URL, and I want to read the contents, Interact with the JavaScript, etc.

I tried

XAML:

<WebView Name="wv1" LoadCompleted="wv1_LoadCompleted" />

C# code:

private void wv1_LoadCompleted(object sender, NavigationEventArgs e)
{
    var uri = e.Uri;

    var c = e.Content;
}

The problem is that the e.Uri is returned, but the e.Content is null.

How to access the DOM? How can I do that?

Upvotes: 1

Views: 1257

Answers (1)

Nico Zhu
Nico Zhu

Reputation: 32775

The problem is that the e.Uri is returned, but the e.Content is null.

The Content property of NavigationEventArgs is used to get the root node of the target page's content. The page is xaml page but not web page. You could verify it with Frame.Navigated event. When page navigated you could get value of Content.

private void RootFrame_Navigated(object sender, NavigationEventArgs e)
{
    System.Diagnostics.Debug.WriteLine(e.Content.ToString()); 
}

If you want to get the web page content. you could refer this reply. With some updates:

To enable an external web page to fire the ScriptNotify event when calling window.external.notify, you must include the page's Uniform Resource Identifier (URI) in the ApplicationContentUriRules section of the app manifest.

The follow eval method used to get body html.

string functionString = @"window.external.notify(document.getElementsByTagName('body')[0].innerHTML)";
await Test.InvokeScriptAsync("eval", new string[] { functionString });

And you could get the return value form ScriptNotify event handler.

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

Upvotes: 1

Related Questions