如何使AddWebAllowedObject()函数在UWP项目中工作?

时间:2019-08-03 15:53:48

标签: c# webview uwp windows-runtime windows-10-universal

我想制作一个演示以在WebView的js中调用本机方法,但是失败了。

下面是C#代码:

namespace webviewDemo
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        [AllowForWeb]
        public sealed class MyNativeClass
        {
            public void NativeMethod()
            {
                Debug.WriteLine(".................MyNativeClass::NativeMethod() is invoked!");
            }
        }

        public MainPage()
        {
            this.InitializeComponent();
            MyWebView.NavigationStarting += MyWebView_NavigationStarting;

            Uri navigationUri = new Uri(@"http://10.119.116.160/test/tom/test.html");
            Debug.WriteLine("......................navigate the url");
            MyWebView.Navigate(navigationUri);
        }

        private void MyWebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
        {
            Debug.WriteLine(".................MyWebView_NavigationStarting() is executing");
            MyWebView.AddWebAllowedObject("nativeObject", new MyNativeClass());
        }
    }
}

下面是test.html源代码:

<html>
<head>
    <script type='text/javascript'>
        nativeObject.NativeMethod(); // Call the projected WinRT method.
    </script>
</head>
</html>

该应用开始运行时,输出日志如下:

......................navigate the url
.................MyWebView_NavigationStarting() is executing

Package.appxmanifest:

  <uap:ApplicationContentUriRules>
    <uap:Rule Type="include" Match="http://10.119.116.160/test/tom/test.html" WindowsRuntimeAccess="all"/>
  </uap:ApplicationContentUriRules>

如您所见,NativeMethod()函数日志未打印,这意味着根本不会调用它。 如何解决? 谢谢!

1 个答案:

答案 0 :(得分:0)

要使其正常工作,“ nativeObject”必须是Windows运行时组件。在您的代码示例中,它只是一个普通的C#类。

实现C#WinRT组件的最简单方法是将一个新项目添加到类型为“ C#-Windows运行时组件”的解决方案中,然后从您的应用程序项目中添加一个对此的引用。然后像往常一样在新项目中实现C#代码。

enter image description here