I need JavaScript in a UWP (Windows 10) WebView to call a C# method. I followed the instruction on how to use AddWebAllowedObject, but when JavaScript calls the C# function, I get this javascript error:
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'getAppVersion'
As you see in javascript, "window.SCObject" is a valid object, but "window.SCObject.getAppVersion()" throws an error! Any idea why?
Here's my code C# code:
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);
}
}
}
Here's my 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>
Here's my 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>
Thank you.
I saw that the HtmlCommunicator was defined in the same project, it would not work.
You need to create a separate windows universal windows runtime component project.
The MSDN documentation also has mentioned this point:
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.
I've helped you test in a separate windows runtime component. It worked well.
User contributions licensed under CC BY-SA 3.0