I'm trying to call a function in JavaScript via Java. This works fine when directly reading a script as a string but I'm using CompiledScripts.
When I do this with a compiled script it gives me method not found if I also add bindings. Without bindings it works but of course the function fails because it needs the bindings.
Any ideas?
CompiledScript script = ... get script....
Bindings bindings = script.getEngine().createBindings();
Logger scriptLogger = LogManager.getLogger("TEST_SCRIPT");
bindings.put("log", scriptLogger);
//script.eval(bindings); -- this way fails
script.eval(); // -- this way works
Invocable invocable = (Invocable) script.getEngine();
invocable.invokeFunction(methodName);
TIA
You can call JavaScript function inside the Java file.
The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
LiveConnect is a technique that allows Java and JavaScript to communicate with each other. It allows your Java class to call JavaScript methods and access the JavaScript environment. JavaScript can also access Java objects and invoke methods on them.
Here's the solution if any one else bumps into this.
import java.util.*;
import javax.script.*;
public class TestBindings {
public static void main(String args[]) throws Exception {
String script = "function doSomething() {var d = date}";
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
Compilable compilingEngine = (Compilable) engine;
CompiledScript cscript = compilingEngine.compile(script);
//Bindings bindings = cscript.getEngine().createBindings();
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
for(Map.Entry me : bindings.entrySet()) {
System.out.printf("%s: %s\n",me.getKey(),String.valueOf(me.getValue()));
}
bindings.put("date", new Date());
//cscript.eval();
cscript.eval(bindings);
Invocable invocable = (Invocable) cscript.getEngine();
invocable.invokeFunction("doSomething");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With