Taritsyn / JavaScriptEngineSwitcher

JavaScript Engine Switcher determines unified interface for access to the basic features of popular JavaScript engines. This library allows you to quickly and easily switch to using of another JavaScript engine.
Apache License 2.0
439 stars 49 forks source link

Callback from JavaScript to C# #94

Closed CzaiStefanB closed 2 years ago

CzaiStefanB commented 3 years ago

Hello,

is it possible to insert a callback function from JavaScript code to C# code as parameter? I tried it like that:

C#: public void CSharpMethodWhichShouldReceiveJavaScriptCallback(object javaScriptCallbackWithParameter) { MyCSharpClass parameterForCallback = new MyCSharpClass(); dynamic callback = javaScriptCallbackWithParameter; callback(parameterForCallback); }

JavaScriptEngine.EmbedHostObject("CSharpMethodWhichShouldReceiveJavaScriptCallback", delegateToMethod);

JavaScript: function callbackFunctionWhichShouldBeCalledFromCSharp(parameter) { // do something with parameter which should be of type MyCSharpClass }

CSharpMethodWhichShouldReceiveJavaScriptCallback(callbackFunctionWhichShouldBeCalledFromCSharp);

The problem is, that the "javaScriptCallbackWithParameter" in the C# method is of type JsValue (ValueType is Function) and I don't know how to call the function then. Perhaps you can give me a hint how to solve this.

Thanks and best regards, Stefan

Taritsyn commented 3 years ago

Hello, Stefan!

You can use the Execute or Evaluate method of JS engine with JSON serialization:

string serializedParameterForCallback = JsonConvert.SerializeObject(parameterForCallback);
jsEngine.Execute("callbackFunctionWhichShouldBeCalledFromCSharp(" + serializedParameterForCallback + ");");
CzaiStefanB commented 3 years ago

Hello Andrey,

thanks for the tip with the serialization. Unfortunately, this probably doesn't work for me because the parameter is a complex C# type that can't be serialized to string. I have now solved the problem by implementing the C# method entirely in JavaScript and making it known in the JS engine. From my side, this would solve the case for now.

Thanks and best regards, Stefan