【发布时间】:2017-01-05 20:05:35
【问题描述】:
我想将内容注入到从 WebView 控件调用的网页中,html 代码是:
<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>
我从 this tutorial 尝试过这个:
string functionString = String.Format("document.getElementById('header').getElementsByTagName('h2')[0].innerHTML = 'new text';");
await webView1.InvokeScriptAsync("eval", new string[] { functionString });
但这会产生错误。我不擅长 javascript 那么如何更改 h2 标签内的文本?
Xaml 代码:
<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代码:
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;
}
我得到的错误:
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:
重现问题:
- 创建一个 Template10 汉堡包模板
- 添加一个新的 xaml 页面,比如 team.xaml 并将这个页面添加到 hamburger shell(一个新的汉堡按钮来导航到这个页面)
- 在 team.xaml 中复制我的代码。
- 现在运行它并从汉堡菜单导航到此页面。
- 这将产生上述错误。
提前致谢!
【问题讨论】:
-
“但这会产生错误。” - 您需要包含确切的错误消息,以及预期的行为以及观察到的行为。
-
我无法重现您的问题。你的代码是对的。您如何将页面加载到`WebView` 以及何时调用
InvokeScriptAsync方法?您能否分享一个可以重现您的问题的minimal reproducible example?
标签: javascript c# xaml webview uwp