Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax script how to call a function in JavaScript from Java

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

like image 615
sproketboy Avatar asked Apr 25 '10 23:04

sproketboy


People also ask

Can we call JavaScript function from Java?

You can call JavaScript function inside the Java file.

How do you call my function in JavaScript?

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.

How do you communicate between Java and JavaScript?

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.


1 Answers

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");
    }
}
like image 119
sproketboy Avatar answered Oct 20 '22 00:10

sproketboy