By using Java Scripting API, I am able to execute JavaScript within Java. However, can someone please explain what I would need to add to this code in order to be able to call on functions that are in C:/Scripts/Jsfunctions.js
import javax.script.*; public class InvokeScriptFunction { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); // JavaScript code in a String String script1 = "function hello(name) {print ('Hello, ' + name);}"; String script2 = "function getValue(a,b) { if (a===\"Number\") return 1; else return b;}"; // evaluate script engine.eval(script1); engine.eval(script2); Invocable inv = (Invocable) engine; inv.invokeFunction("hello", "Scripting!!"); //This one works. } }
import javax. script. *; public class InvokeScriptFunction { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.
Calling JavaScript from JavaTo call Nashorn JavaScript from a Java 8 program, you basically need to make a new ScriptEngineManager instance and use that ScriptEngineManager to load the Nashorn script engine by name.
If your JavaScript code is based on the DOM structure of the document and you really, really want to reuse it, then you can write a browser plugin (for example for Chrome), let the Java code start browser instances on the right pages, and let the plugin send data back to the Java code through AJAX.
Use ScriptEngine.eval(java.io.Reader)
to read the script
ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); // read script file engine.eval(Files.newBufferedReader(Paths.get("C:/Scripts/Jsfunctions.js"), StandardCharsets.UTF_8)); Invocable inv = (Invocable) engine; // call function from script file inv.invokeFunction("yourFunction", "param");
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