Tuesday, 25 February 2014

Calling Javascript method from Java class

We can also call javascript method from Java file .

1. First create a JS file
    Now lets create a js file myJS.js and put below line in the file

var functionDemo = function() { return "hello user"; };

and save this file in C drive (You can save it in any directory but you have to mention it in the java file)

2. Create a java class which will call this method

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

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

public class JavascriptFunctionCallingFromJava {    

    public static void main(String[] args)
            throws ScriptException, NoSuchMethodException {
    String jsString=null;
    try {
InputStreamReader fd=new FileReader("C:\\myJS.js");
BufferedReader br=new BufferedReader(fd);
try {
jsString=br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (FileNotFoundException e) {
e.printStackTrace();
}
        ScriptEngine se = new ScriptEngineManager().getEngineByName("javascript");        // Retrieving the Javascript engine
        if ( Compilable.class.isAssignableFrom(se.getClass()) ) {
            Compilable c = (Compilable) se;
            CompiledScript cs = c.compile(jsString);//We can compile javascript
            cs.eval();
        } else {
            se.eval(jsString);
        }
        if ( Invocable.class.isAssignableFrom(se.getClass()) ) {
            Invocable i = (Invocable) se;
            System.out.println("What our functionDemo in myJS.js returns is:"
                + i.invokeFunction("functionDemo"));
        } else {
            System.out.println( "calling method not supported");
        }
    }
}

Output :
What our functionDemo in myJS.js returns is:hello


No comments:

Post a Comment