Uwpbeginner Uwpbeginner - 1 year ago 188
C# Question

Modify Transmitted data in Webview Control

I want to inject content into my web page called from WebView Control and the html code is:

<section id="header" class="header-section section-padding">
<div class="container">
<div class="row">
<div class="text-center">
<h2 class="section-title">Text I Want to Change</h2>

I tried this from this tutorial:

string functionString = String.Format("document.getElementById('header').getElementsByTagName('h2')[0].innerHTML = 'new text';");
await webView1.InvokeScriptAsync("eval", new string[] { functionString });

But this is generating error.I am not good in javascript so how do I change the text inside

Xaml Code:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<WebView x:Name="WebView"
Source="http://info.vit.ac.in/gravitas2015/tg15/index.html" />
<ProgressRing x:Name="ProgressRing"
IsActive="True" />

Cs code:

private async void WebView_LoadCompleted(object sender, NavigationEventArgs e)
string functionString = String.Format("document.getElementById('header').getElementsByTagName('h2')[0].innerHTML = 'new text';");
await WebView.InvokeScriptAsync("eval", new string[] { functionString });
ProgressRing.Visibility = Visibility.Collapsed;

Error that i am getting:

System.Exception was unhandled by user code
Message=Exception from HRESULT: 0x80020101
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at WindowsApp2.Views.Organisers.<WebView_LoadCompleted>d__1.MoveNext()

To reproduce the issue:

  1. Create a Template10 Hamburger Template

  2. Add a new xaml page say team.xaml and add this page to hamburger shell(a new hamburger button to navigate to this page)

  3. In team.xaml copy my code.

  4. Now run it and navigate to this page from hamburger Menu.

  5. This will generate the above error.

Thanks in advance!

Answer Source

The problem here is that there is no section whose id is "header" in your html page:http://info.vit.ac.in/gravitas2015/tg15/index.html.

If we test the JavaScript code in web browser (e.g. Edge), we will find it will throw an error like following:
enter image description here

And this is the reason why we get exception while calling InvokeScriptAsync in code-behind. I'm not sure which section you want to change, but if you edit the JavaScript string like following, your code should be able to work.

string functionString = String.Format("document.getElementById('portfolio').getElementsByTagName('h2')[0].innerHTML = 'new text';");

Besides this, WebView.LoadCompleted event may be altered or unavailable for releases after Windows 8.1. Instead, please use NavigationCompleted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download