【问题标题】:Why doesn't UWP WebView AddWebAllowedObject work?为什么 UWP WebView AddWebAllowedObject 不起作用?
【发布时间】: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


【解决方案1】:

通过测试,您需要在您的 html 内容中以小写形式调用 Dial 类的 Greet() 方法,如 document

private void WebView_Loaded(object sender, RoutedEventArgs e)
{
    wv.NavigateToString("" +
        "<html>" +
        "<head>" +
        "<script>function hi() { dial.greet(); }</script>" +
        "</head>" +
        "<body>" +
        "</body>" +
        "</html>"
    );
}

【讨论】:

  • 有效!谢谢,我花了一个下午的时间在文档上,却没有意识到更改的符号。也许他们应该更多地强调它?
猜你喜欢
  • 1970-01-01
  • 2021-11-21
  • 2021-09-20
  • 1970-01-01
  • 2017-10-10
  • 2023-03-21
  • 1970-01-01
  • 2018-04-03
  • 1970-01-01
相关资源
最近更新 更多