简体   繁体   中英

Why doesn't UWP WebView AddWebAllowedObject work?

I'm trying to use the WebView's AddWebAllowedObject method but, at runtime, an error is returned when is invoked the function that uses it. Am I doing something wrong? Thanks in advance.

Notes: Dial class is contained in runtime project.

    [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
        }
    }

By testing, you need to call the Greet() method of Dial class in lowercase in your html content as in this document .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM