1

I am playing with Webview2 and tried to pass JavaScript object to C# method of registered Host Object, but I do not know how to retrieve its content.

public object[] TestCall(string arg1, object arg2)
{
    // arg2.item1 // This don't work
    // Including arg2 in array will return it back to JavaScript, so it is stored some where
    return new List<object>() { "item1", "item2", 123, false, arg1, arg2 }.ToArray();
}
// await window.chrome.webview.hostObjects.dotNetObject.TestCall("Hello world", { item1: "value1", item2: 1234 });

I tried to look up official C# samples, but none demonstrated how to pass JavaScript object into method of HostObject.

I had worked around this by using JSON to exchange data between C# and JavaScript.

Yet I'm still puzzled.

My question:

How do I pass any JavaScript object into method of HostObject without stringify it to JSON?

Is there anyway to get content out of JS object I received in arg2?

What I tried

  • I used System.Runtime.InteropServices.Marshal.GetIDispatchForObject(arg2); to get a pointer.

    But I do not know what to do with it, since I do not have knowledge of COM or IDispatch.

  • I tried casting it to ExpandoObject, Invalid cast

  • I tried casting it to dynamic, successful, but ((dynamic)arg2).item1 throws NotImplementedException

10
  • Does this answer your question? Setting an object from .NET to JavaScript code through WebView2 Commented Feb 19, 2022 at 21:04
  • Here's another example: learn.microsoft.com/da-dk/dotnet/api/… Commented Feb 19, 2022 at 21:32
  • No. I am not trying to addHostObjectToScript(). I already did that. I have added a host object with a method TestCall. I am trying to pass JavaScript object to it like this hostobj.TestCall(1234, { item1: 1111, item2: 2222 });. My problem is I cannot get the data in supplied JavaScript object in C# Commented Feb 20, 2022 at 16:06
  • Try this: public dynamic[] TestCall(string arg1, dynamic arg2) (the object type does not have those proerties). Commented Feb 20, 2022 at 18:17
  • 1
    Under the section 'Passing Objects to .NET' under weblog.west-wind.com/posts/2021/Jan/26/… , the article suggests this isn't possible. But, obviously, both the article and this question are dated. Commented Dec 8, 2022 at 17:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.