Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
add comment

1 Answer

don't known about Envjs, but why simulate a browser environment in java?

for the second question:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
Compilable compilable = (Compilable) engine;
Bindings bindings = engine.createBindings(); 
String script = "function add(op1,op2){return op1+op2} add(a, b)"; 
CompiledScript jsFunction = compilable.compile(script);
bindings.put("a", 1);bindings.put("b", 2); //put java object into js runtime environment
Object result = jsFunction.eval(bindings);
System.out.println(result); 

you can put whatever object into the bindings, a map, a list, or a pojo.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.