I want to call the Javascript inside my Java class but not able to find correct way. I read somewhere it can be done using Nashorn. could someone please let me know the exact way.
-
1Upvoters...any specific reason for upvoting this question?Krishna Prashatt– Krishna Prashatt2018-06-04 13:20:10 +00:00Commented Jun 4, 2018 at 13:20
-
1No Idea Sir, any issues?Sumit Sood– Sumit Sood2018-06-06 13:30:17 +00:00Commented Jun 6, 2018 at 13:30
-
1Nothing personal.. just wanted to know on what basis people are upvoting a question.Krishna Prashatt– Krishna Prashatt2018-06-06 13:36:58 +00:00Commented Jun 6, 2018 at 13:36
Add a comment
|
1 Answer
You can call JavaScript using "ScriptEngineManager" as below.
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine engine = scriptEngineManager.getEngineByName("nashorn");
try {
engine.eval(new FileReader("src\\demo.js"));
Invocable invocable = (Invocable)engine;
Object result = invocable.invokeFunction("fun1", "User");
System.out.println(result);
} catch (ScriptException e) {
e.printStackTrace();
}
And you JS file demo.js will looks something like below.
var fun1 = function(name){
print('Hi,'+name);
return "Greeting from javascript";
}