kekyo / DupeNukem

WebView attachable full-duplex asynchronous interoperable independent messaging library between .NET and JavaScript.
Apache License 2.0
18 stars 0 forks source link

Support Invoking Modules/Classes from JS in C# #20

Open geocine opened 1 year ago

geocine commented 1 year ago

I can see this is possible from C# to JS like so

var calculator = new Calculator();
messenger.RegisterObject(calculator)

How do I do this for JS? It seems I can only invoke functions from the window context.

kekyo commented 1 year ago

Does this mean that you want to call a member function of an object on the JS side as an instance of a class object from the .NET side?

.NET Proxy feature on https://github.com/kekyo/DupeNukem/issues/5#issue-1183238546 for example?

This issue eventually pivoted to being able to pass a callback function. The reason is that I felt that if the callback function could be implemented, it would no longer be necessary. However, the callback function is a different method than the realization of a proxy feature, so it is not exactly a replacement....

Do you think this function should be there?

geocine commented 1 year ago

I think not to this extent but I want to be able to call functions from a class/module from JavaScript in C#

Let's say this is JS

let calculator = new Calculator(); // declaring using let will not attach calculator to window
messenger.RegisterObject(calculator) // so we need a way to expose it to C#

I should be able to do this in C#

invokeClientMethod(`calculator.add`, 1,2);
kekyo commented 1 year ago

@geocine Sorry too later :(

I remembered that I had implemented it to accept that operation, so I wrote some test code:

https://github.com/kekyo/DupeNukem/pull/21/commits/4132b6b8c21bc1aef06e14d0c26a384244102bfb

JavaScript classes like this one:

class JSCalculator {
  async add(a, b) { return a + b; }
  async sub(a, b) { return a - b; }
};
var jscalc = new JSCalculator();

It can be called like this:

            var result_jscalc_add = await messenger.InvokePeerMethodAsync<int>(
                "jscalc.add", 1, 2);

If you could check out this commit and give it a try, you can confirm this. However, it may just be my environment, but now in Edge WebView2, the apply function in the JavaScript is not working correctly, so the call after the Ready event does not complete (I checked all other environments, only Edge WebView2 is abnormal).