Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call external javascript functions from java code

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.        } } 
like image 958
MRK187 Avatar asked Apr 04 '14 07:04

MRK187


People also ask

Can I call JavaScript function in Java?

import javax. script. *; public class InvokeScriptFunction { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.

Can you execute JavaScript code from Java 8 code base?

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.

How can I use JavaScript and Java together?

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.


1 Answers

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"); 
like image 143
user432 Avatar answered Oct 04 '22 03:10

user432