【问题标题】:UWP WebView Javascript "Object doesn't support property or method"UWP WebView Javascript“对象不支持属性或方法”
【发布时间】:2017-07-10 09:30:08
【问题描述】:

我需要 UWP (Windows 10) WebView 中的 JavaScript 来调用 C# 方法。我按照有关如何使用 AddWebAllowedObject 的说明进行操作,但是当 JavaScript 调用 C# 函数时,我收到了这个 javascript 错误:

0x800a01b6 - JavaScript 运行时错误:对象不支持属性 或方法“getAppVersion”

正如您在 javascript 中看到的,“window.SCObject”是一个有效对象,但“window.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>

谢谢。

【问题讨论】:

    标签: javascript c# windows webview uwp


    【解决方案1】:

    我看到 HtmlCommunicator 是在同一个项目中定义的,它不起作用。

    您需要创建一个单独的 windows 通用 windows 运行时组件项目。

    MSDN 文档也提到了这一点:

    传递给 AddWebAllowedObject(System.String,System.Object) 的对象必须从独立于应用程序集的 Windows 运行时组件导入。这对于 AllowForWeb 属性是由 WebView 安全子系统标识的属性是必要的。如果您使用应用项目中的类,则 AddWebAllowedObject(System.String,System.Object) 不起作用。

    我已经帮助您在单独的 Windows 运行时组件中进行了测试。效果很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 2015-04-14
      • 2020-09-03
      • 2015-04-09
      • 2014-01-12
      相关资源
      最近更新 更多