Home > Mobile >  CoreWebView2.AddHostObjectToScript throws System.Exception
CoreWebView2.AddHostObjectToScript throws System.Exception

Time:06-24

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

  1. Create an UWP project
  2. Add necessary nuget packages (Microsoft.Web.Webview2 latest stable release and Microsoft.UI.Xaml 2.8.0-prerelease)
  3. Add WebView2 component to MainPage.xaml
  4. Create HostObject class with necessary tags
  5. Add code for navigation starting or navigation completed method in WebView2 (MainPage.xaml.cs)
  6. Ensure CoreWebView2 is not null by calling myWebView.EnsureCoreWebView2Async(); inside method
  7. 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);
}

Exception Thrown Image

CodePudding user response:

I got my answer from github's community at WebView2 Feedback

  • Related