2017-02-20 58 views
2

UWP(Windows 10)WebViewでJavaScriptを使用してC#メソッドを呼び出す必要があります。私はAddWebAllowedObjectを使用する方法の指示に従ったが、JavaScriptはC#の関数を呼び出すとき、私はこのjavascriptのエラーを取得:あなたはJavaScriptで見たようUWP WebView Javascript "オブジェクトがプロパティまたはメソッドをサポートしていません"

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

を、「window.SCObjectは、」有効なオブジェクトですが、「窓.SCObject.getAppVersion() "はエラーをスローします。どんな考え?

は、ここに私のコードC#のコードです:

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

ありがとう

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です。

答えて

3

HtmlCommunicatorが同じプロジェクトで定義されていることがわかりましたが、うまくいきませんでした。

別の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.

私は別のWindowsランタイムコンポーネントであなたのテストを助けてきました。それはうまくいった。

関連する問題