Call external javascript functions from java code
Asked Answered
C

3

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.      
 }
}
Clayborne answered 4/4, 2014 at 7:27 Comment(0)
P
61

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");
Psychochemical answered 4/4, 2014 at 7:40 Comment(6)
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.Hernando
Which window or browser are you referring to?Clayborne
what was the solution?Dunkin
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));Lorenz
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.Derogate
@Derogate you can try with load('path/to/Mom‌​ent.js'); inside your script.Mikaelamikal
R
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);
        }
Roti answered 1/1, 2018 at 19:5 Comment(1)
Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value 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.Markup
E
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.

Emu answered 10/5, 2018 at 17:41 Comment(1)
FYI...for those who have moved to OpenJDK, because of Oracle's Java licensing changes or for whatever reason, Nashorn is deprecated in OpenJDK. openjdk.java.net/jeps/335Rounce

© 2022 - 2024 — McMap. All rights reserved.