Reputation: 405
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>
</div>
</div>
</div>
</section>
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 h2
tag?
Xaml Code:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<WebView x:Name="WebView"
LoadCompleted="WebView_LoadCompleted"
Source="http://info.vit.ac.in/gravitas2015/tg15/index.html" />
<ProgressRing x:Name="ProgressRing"
Width="100"
Height="100"
Foreground="BlueViolet"
IsActive="True" />
</Grid>
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
HResult=-2147352319
Message=Exception from HRESULT: 0x80020101
Source=mscorlib
StackTrace:
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()
InnerException:
To reproduce the issue:
Thanks in advance!
Upvotes: 2
Views: 566
Reputation: 15758
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:
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.
Upvotes: 2