CoreWebView2.AddHostObjectToScript throws System.Exception: 'The group or resource is not in the correct state to perform the requested operation.' Version SDK: 1.0.1245.22 latest stable - (and Microsoft.UI.Xaml 2.8.0-prerelease.210927001) Runtime: Framework: UWP OS: Windows 11, build 22000
Reproduce Steps
- Create an UWP project
- Add necessary nuget packages (Microsoft.Web.Webview2 latest stable release and Microsoft.UI.Xaml 2.8.0-prerelease)
- Add WebView2 component to MainPage.xaml
- Create HostObject class with necessary tags
- Add code for navigation starting or navigation completed method in WebView2 (MainPage.xaml.cs)
- Ensure CoreWebView2 is not null by calling myWebView.EnsureCoreWebView2Async(); inside method
- Try use myWebView.CoreWebView2.AddHostObjectToScript("HostObject", hostObject); inside method (Also tried to make a new project uwp (as Windows Runtime Component) and create the HostObject class there but still same exception. In addition tried to change tags on HostObject class but still same issue)
Example of HostObject class:
[AllowForWeb]
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class JsCallbacksUwp
{
public JsCallbacksUwp()
{
}
}
Example code for Navigation Completed that throws the exception:
private async void WebView2_NavigationCompleted(WebView2 sender, CoreWebView2NavigationCompletedEventArgs args)
{
await sender.EnsureCoreWebView2Async();
var browserHostObject = new JSCallbacksUwp();
sender.CoreWebView2.AddHostObjectToScript("HostObject", browserHostObject);
}
CodePudding user response:
I got my answer from github's community at WebView2 Feedback