Monday, 7 December 2015

Java - Call javascript functions from java

Calling external javascript function.


Sample Program:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

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

public class SampleJsTest {

public static void main(String[] args) throws NoSuchMethodException, ScriptException, IOException {
//create a script engine manager
   ScriptEngineManager manager = new ScriptEngineManager();
//create a JavaScript engine
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get(System.getProperty("user.dir")+"\\js\\myscripts.js"), StandardCharsets.UTF_8));
Invocable inv = (Invocable) engine;
//call function from script file
double result = (double) inv.invokeFunction("addNumbers", "10","4");
System.out.println(result);
String name = (String) inv.invokeFunction("greeting", "\"Praveen\"");
        System.out.println(name);
}
}



Note:
Adds two int's in javasript but returns double. 


Writing javascript in the java code and calling javascript function


Sample Program:
import java.io.IOException;

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

public class SampleJsTest {

public static void main(String[] args) throws NoSuchMethodException, ScriptException, IOException {
//create a script engine manager
ScriptEngineManager manager = new ScriptEngineManager();
//create a JavaScript engine
   ScriptEngine engine = manager.getEngineByName("JavaScript");

//Javascript inside java code
   //JavaScript code in a String
   String script1 = (String) "function add(a,b) {return (parseInt(a)+parseInt(b))}";
   engine.eval(script1);
  
   String script2 = (String) "function greeting(name) {return 'Welcome '+name}";
   engine.eval(script2);

   Invocable inv = (Invocable) engine;

   double result = (double) inv.invokeFunction("add", "1","4" );  
   System.out.println("Add : "+result);
   String name = (String) inv.invokeFunction("greeting", "Praveen Kumar");
   System.out.println("Name : "+name);
}
}

No comments:

Post a Comment