Setting an object from .NET to JavaScript code through WebView2

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);    } } 
Add Comment
1 Answer(s)

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!

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.