5

Thanks in advance,

I want to set an object to the java script code which is contained within a WebPage. I am displaying this Web page in the WPF window that references the WebView2 with Name as 'webView'.

I am pretty new to WebView2 and I am not absolutely sure how to pass 'name' and 'object' in AddHostObjectToScript() method of WebView2 SDK

Here is what I have tried:

[ComVisible(true)]
public class ObjectHandle
{

  public Products(IPriceService priceDetails,IBillService billDetails)
  {  
     PriceDetails = priceDetails;
     BillDetails = billDetails;
  }

  public IPriceService PriceDetails { get; private set; }

  public IBillService  BillDetails { get; private set; }

}

public class WebViewBrowser:Window
{
   public WebViewBrowser()
   {
     InitializeComponent();
     InitializeAsync();
   }

   private void SetScriptingObject
   {
      ObjectHandle objHandle = new ObjectHandle(priceDetails,billDetails);
               
      webView.corewebview2.AddHostObjectToScript("ObjectHandle",objHandle );                                                                            
   }

   async void InitializeAsync()
   {
      await webView.EnsureCoreWebView2Async(null);
   }
}
DotNetSpartan
  • 931
  • 4
  • 20
  • 41

1 Answers1

10

Great question! We plan to update our C# sample apps to show how to use AddHostObjectToScript as it is not obvious.

Classes that you intend to use with AddHostObjectToScript need to be marked with the following attributes:

[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class Example
{

    // Sample property.
    public string Prop { get; set; } = "example";
}

Then later you call AddHostObjectToScript like you're already doing above with an instance of your class and the name set to whatever you want to call your object from script.

webView.CoreWebView2.AddHostObjectToScript("example", new Example());

Then in script you can use that object via chrome.webview.hostObjects.{name of host object}:

const example = chrome.webview.hostObjects.example;
const value = await example.Prop;

For now see the C++ WebView2 documentation and sample code for how to use projected host objects in script. We should add better .NET documentation for this in the future. Thanks!

David Risney
  • 3,886
  • 15
  • 16
  • Thanks @David Risney. I could pass the COM object to JavaScript using above approach ! – DotNetSpartan Jul 22 '20 at 06:02
  • 4
    I tried this method `const example = chrome.webview.hostObjects.example;` It works for a while, but then stops working. A theory says it has to to with JavaScript garbage collection, but I found that if I use `const value = await chrome.webview.hostObjects.example.Prop` directly, instead of `const value = await example.Prop;` then there is no problem. – Magnus Oct 21 '20 at 18:55