我需要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>
謝謝。