Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

By using Java Sripting API, I am able to execute JavaScript within Java. However, can someone please explain what I would need to add to this code for being 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 = (String)"function hello(name) {print ('Hello, ' + name);}";
    String script2 = (String)"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.      
 }
}
share|improve this question
up vote 17 down vote accepted

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");
share|improve this answer
    
Thanks a lot mate – MRK187 Apr 4 '14 at 7:52
    
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 6 at 17:23
    
Which window or browser are you referring to? – MRK187 May 13 at 14:02
    
Thanks, my problem is solved.... :) – Hassan Aug 5 at 6:21
1  
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 at 9:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.