【发布时间】:2020-11-22 18:59:12
【问题描述】:
我正在尝试使用 WebView 的 AddWebAllowedObject 方法,但是在运行时,调用使用它的函数时会返回错误。难道我做错了什么? 提前致谢。
注意:Dial 类包含在运行时项目中。
[AllowForWeb]
public sealed class Dial
{
public void Greet()
{
Debug.WriteLine("Hello!");
}
}
public sealed partial class MainPage : Page
{
public MainPage()
{
InitializeComponent();
}
private void WebView_Loaded(object sender, RoutedEventArgs e)
{
wv.NavigateToString("" +
"<html>" +
"<head>" +
"<script>function hi() { dial.Greet(); }</script>" +
"</head>" +
"<body>" +
"</body>" +
"</html>"
);
}
private void WebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
wv.AddWebAllowedObject("dial", new Dial());
}
private async void WebView_DOMContentLoaded(WebView sender, WebViewNavigationStartingEventArgs args)
{
await wv.InvokeScriptAsync("hi", new string[] {}); // Error 0x80020101
}
}
【问题讨论】:
-
我怀疑“Debug.Writeline()”在 JavaScript 中不起作用。尝试将“Greet()”改为返回一个字符串,然后让“hi()”函数调用 alert(dial.Greet())。另外,我认为您应该像这样调用 InvokeScriptAsync(): InvokeScript("eval", new string[] { "'hi()" })
-
解决方案在接受的答案中。无论如何感谢您的关注!
标签: javascript c# webview uwp