gpt4 book ai didi

javascript - UWP WebView Javascript "Object doesn' t 支持属性或方法”

转载 作者:可可西里 更新时间:2023-11-01 10:03:38 27 4
gpt4 key购买 nike

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

0x800a01b6 - JavaScript runtime error: Object doesn't support property or method '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>

谢谢。

最佳答案

我看到在同一个项目中定义了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.

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

关于javascript - UWP WebView Javascript "Object doesn' t 支持属性或方法”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42355804/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com