2017-02-20 13 views
2

Мне нужен JavaScript в UWP (Windows 10) WebView для вызова метода C#. Я следовал инструкции о том, как использовать AddWebAllowedObject, но когда JavaScript вызывает функцию C#, я получаю эту ошибку яваскрипта: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 для окон.

документация 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.

я помог вам проверить в отдельном компоненте окна во время выполнения. Он работал хорошо.

Смежные вопросы