Closed CzaiStefanB closed 2 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 + ");");
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
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