Tuesday, September 8, 2020

Call javascript function from java

 Call any function in JavaScript(JS) file from java code

1.    we need to import following inbuilt java classes

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

2.   Code to call any function of javascript file.

        ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
      engine.eval(new InputStreamReader(this.getClass().getResourceAsStream("/Scripts/JavascriptFile.js")));         
       
 // put file JavascriptFile.js inside your project class path Scripts folder or anywhere you want

        Invocable inv = (Invocable) engine;
        ScriptObjectMirror obj = (ScriptObjectMirror) inv.invokeFunction("functionName",          parameterString);

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home