51

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.      
 }
}
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
MRK187
  • 1,545
  • 2
  • 13
  • 20

3 Answers3

60

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");
user432
  • 3,506
  • 17
  • 24
  • 2
    Yes, it's useful, thanks. How can we use Window in the provided javascript since through java code there will be no browser for this. – sandeep kale Feb 06 '15 at 17:23
  • Which window or browser are you referring to? – MRK187 May 13 '15 at 14:02
  • what was the solution? – Fahim Oct 14 '15 at 00:22
  • 2
    In case difficulties in loading relative path use below code. `URL fileUrl = getClass().getResource("js/WebWorker.js"); engine.eval(Files.newBufferedReader(Paths.get(fileUrl.toURI()),StandardCharsets.UTF_8));` – Mano Oct 28 '15 at 09:08
  • Hi, I have doubt, I have tried to invoke the function which has dependencies of moment.js library. So i just added the library script as well with that like this `engine.eval(Files.newBufferedReader(Paths.get("/Volumes/Bala/Eclipse Mars/Workspace/ClientWebAccessFullHistory/war/js/Library/Moment.js"), StandardCharsets.UTF_8)); engine.eval(Files.newBufferedReader(Paths.get("/Volumes/Bala/Eclipse Mars/Workspace/ClientWebAccessFullHistory/war/js/newLayout/FullHistory/fullHistory.js"), StandardCharsets.UTF_8));` But it is not available at global scope. – Bala.Raj May 06 '16 at 15:24
  • @Bala.Raj you can try with `load('path/to/Mom‌​ent.js');` inside your script. – Ben Dec 16 '16 at 23:48
2
try {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        System.out.println("okay1");
        FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
        System.out.println("okay2");
        if (fileInputStream != null){
         BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
         engine.eval(reader);
         System.out.println("okay3");
        // Invocable javascriptEngine = null;
         System.out.println("okay4");
        Invocable invocableEngine = (Invocable)engine;
         System.out.println("okay5");
         int x=0;
         System.out.println("invocableEngine is : "+invocableEngine);
         Object object = invocableEngine.invokeFunction("backend_message",x);

         System.out.println("okay6");
        }
        }catch(Exception e) {
            System.out.println("erroe when calling js function"+ e);
        }
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/206345) by showing _why_ this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Mogsdad Jan 01 '18 at 19:10
1

Let us say your jsfunctions.js file has a function "display" and this file is stored in C:/Scripts/Jsfunctions.js

jsfunctions.js

var display = function(name) {
print("Hello, I am a Javascript display function",name);
return "display function return"
}

Now, in your java code, I would recommend you to use Java8 Nashorn. In your java class,

import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

class Test {
public void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
  engine.eval(new FileReader("C:/Scripts/Jsfunctions.js"));
  Invocable invocable = (Invocable) engine;
  Object result;
  result = invocable.invokeFunction("display", helloWorld);
  System.out.println(result);
  System.out.println(result.getClass());
  } catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
    e.printStackTrace();
    }
  }
}

Note: Get the absolute path of your javascript file and replace in FileReader() and run the java code. It should work.

Vasuki Dileep
  • 573
  • 4
  • 10
  • 3
    FYI...for those who have moved to OpenJDK, because of Oracle's Java licensing changes or for whatever reason, Nashorn is deprecated in OpenJDK. https://openjdk.java.net/jeps/335 – HankNessip Oct 31 '19 at 16:09