2017-02-20 49 views
2

我需要UWP(Windows 10)WebView中的JavaScript來調用C#方法。我跟着如何使用AddWebAllowedObject指令,但是當JavaScript調用C#的功能,我得到這個JavaScript錯誤:UWP WebView Javascript「對象不支持屬性或方法」

0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'getAppVersion'

正如你在JavaScript中看到,「window.SCObject」是一個有效的對象,但「窗口.SCObject.getAppVersion()「會引發錯誤!任何想法爲什麼?

這裏是我的代碼C#代碼:

namespace Test 
{ 
    [AllowForWeb] 
    public sealed class HtmlCommunicator 
    { 
     public string getAppVersion() 
     { 
      PackageVersion version = Package.Current.Id.Version; 
      return String.Format("{0}.{1}.{2}.{3}", 
           version.Major, version.Minor, version.Build, version.Revision); 
     } 
    } 


    public sealed partial class MainPage : Page 
    { 
     public MainPage() 
     { 
      this.InitializeComponent(); 
      this.HtmlWebView.Navigate(new Uri("ms-appx-web:///Assets/HTMLPage1.html")); 
     } 

     private HtmlCommunicator communicationWinRT = new HtmlCommunicator(); 
     private void HtmlWebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) 
     { 
      this.HtmlWebView.AddWebAllowedObject("SCObject", communicationWinRT); 
     } 
    } 
} 

這裏是我的XAML:

<Page 
x:Class="Test.MainPage" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:Test" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d"> 

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
    <WebView NavigationStarting="HtmlWebView_NavigationStarting" x:Name="HtmlWebView" /> 
</Grid> 

這裏是我的javascript:

<script type="text/javascript"> 
    function HtmlGetAppVersion() { 
     if (window.SCObject) { //this is true 
      var version = window.SCObject.getAppVersion(); //error occurs here 
      console.log("Version: " + version); 
     } 
    } 
</script> 

謝謝。

回答

3

我看到HtmlCommunicator是在同一個項目中定義的,它不起作用。

您需要創建一個單獨的Windows通用Windows運行時組件項目。

MSDN文件也提到了這一點:

The object passed into AddWebAllowedObject(System.String,System.Object) must be imported from a Windows Runtime component that is separate from the app assembly. This is necessary for the AllowForWeb attribute to be property identified by the WebView security subsystem. If you use a class from your app project, AddWebAllowedObject(System.String,System.Object) does not work.

我已經幫助你在一個單獨的窗口中運行時組件測試。它運作良好。

相關問題