I am trying to execute Javascript code from Java. Javascript code uses jquery so I prepend the jquery.js before my code. But it throws following exception,
Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "window" is not defined. (<Unknown source>#1) in <Unknown source> at line number 1
As I run this from the Java code, I understand that it does not have access to the window object so above exception. I found that EnvJs provides the implementation for the required environment so I tried to load that first by putting its content first while generating the script content to eval. But run into following exception,
Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: TypeError: Cannot call property getCurrentContext in object [JavaPackage org.mozilla.javascript.Context]. It is not a function, it is "object". (<Unknown source>#1247) in <Unknown source> at line number 1247
Following is the code snippet,
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String script = "Envjs code" + "jQuery code" + "my java script"; //code of envjs + jquery from the link provided at the end
engine.eval(script);
Invocable inv = (Invocable) engine;
inv.invokeFunction("myFunc", obj1, obj2);
I do not use any browser features so do not require object's like window. So ideally I do not want to load Envjs. Please let me know how to load jQuery code.
One more question - How to pass Json Object from Java code to Javascript function as parameter?
http://www.envjs.com/dist/env.rhino.1.2.js
http://code.jquery.com/jquery-1.9.0.min.js