I use Jint to parse JS code and call functions in it. As I use a multithreaded environment, I use the program-parsing approach as indicated in the response to this issue: https://github.com/sebastienros/jint/issues/384
So what I have is a Jint.Parser.Ast.Program
instance. I can iterate through the IFunctionDeclaration
s in it and find my functions. But I don't know how to actually call the functions...
Dim parser As New Jint.Parser.JavaScriptParser
Dim program As Jint.Parser.Ast.Program = parser.Parse(code)
For Each func As Jint.Parser.IFunctionDeclaration In program.FunctionDeclarations
If func.Id.Name = myFunctionName Then
' How to call the function?
End If
Next
I only found a way to execute the whole Program
. I assume that I must do that, so that the functions are actually defined in an engine. But still, how can I call a certain function in my script?
Once your program is executed, just use the same method to execute your function. Example is c#
var parser = new Jint.Parser.JavaScriptParser();
// _parserCache is a static ConcurrentDictionary<string, Jint.Parser.Ast.Program>
var program = _parserCache.GetOrAdd(scriptName, key => parser.Parse(code));
foreach (var func in program.FunctionDeclarations)
{
if (func.Id.Name == myFunctionName)
{
var exec = new Engine();
// The entire program is executed, to define the function
exec.Execute(program);
// now you can call your function
exec.Execute($"{myFunctionName}()");
}
}