我想制作一个演示以在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()函数日志未打印,这意味着根本不会调用它。 如何解决? 谢谢!