Search code examples
.netwebviewwebbrowser-controlchromiumwebview2

'Access is denied' or Promise<Pending> errors seen while accessing the COM object from WebView2 page


Thanks in advance.

I am unable to communicate from JavaScript code to the WebView2 control embedded in WPF application as I am seeing errors like - 'Access is denied', 'Promise Pending' etc. I am not sure what is wrong as everything seems to be correct here.

Here is my piece of code:

The COM Object:

 [ClassInterface(ClassInterfaceType.AutoDual)]
    [ComVisible(true)]
    public class NativeMethods
    {        
        public string SendMessage(string message)
        {
            return message;
        }
    }

The WPF User Control that contains WebView2

 public partial class WebView2Control : UserControl
 {
   public WebView2Control()
   {
      InitializeAsync();
   }
    async void InitializeAsync()
    {
      await webView.EnsureCoreWebView2Async(null);
      WebView_CoreWebView2Ready();
    }

     private void WebView_CoreWebView2Ready()
     {
       webView.CoreWebView2.AddHostObjectToScript("nativeMethods", new NativeMethods());
     }               
}

JavaScript Code in Dev Tools enter image description here


Solution

  • Are you able to share a running version of the project? I tried creating my own new C# WPF app and pasted in parts of your code but it seems to be working for me.

    • For attempt 1, I have a breakpoint on SendMessage and I see the breakpoint hit when I call SendMessage from script.

    • For attempt 2, the sync() method is an async method that waits until the proxy you're calling it on completes before completing itself and giving you a synchronous proxy. So you probably intended for the code of attempt - 3.

    • For attempt 3, this code also works for me. If I set the WebView2.CoreWebView2.Settings.AreHostObjectsAllowed to false I get the same output as what you have there. Ensure that property is set to true or else the script in your page won't have access to objects added via AddHostObjectToScript.

    Another issue to watch out for is any race conditions. Please ensure you are running the script that is accessing your native object after AddHostObjectToScript has completed. In your case I'm guessing you're running the code you have listed and then opening dev tools and manually trying different things from the console, so this is probably not an issue for you.