我正在尝试从Java执行Javascript代码。 Javascript代码使用jquery所以我在我的代码之前添加了jquery.js。但它抛出了异常,
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
当我从Java代码运行它时,我理解它无法访问窗口对象,因此异常。我发现EnvJs提供了所需环境的实现,因此我尝试首先将其内容放在第一位,同时将脚本内容生成为eval。但遇到以下异常,
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
以下是代码段
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);
我不使用任何浏览器功能,因此不需要像窗口一样的对象。理想情况下,我不想加载Envjs。请告诉我如何加载jQuery代码。
还有一个问题 - 如何将Json Object从Java代码传递给Javascript函数作为参数?
http://www.envjs.com/dist/env.rhino.1.2.js
http://code.jquery.com/jquery-1.9.0.min.js
答案 0 :(得分:1)
使用Envjs指南(http://www.envjs.com/doc/guides#running-embed)中的说明,使用Rhino可能更容易。
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.tools.shell.Global;
import org.mozilla.javascript.tools.shell.Main;
...
Context cx = ContextFactory.getGlobal().enterContext();
cx.setOptimizationLevel(-1);
cx.setLanguageVersion(Context.VERSION_1_5);
Global global = Main.getGlobal();
global.init(cx);
Main.processSource(cx, "path/to/your/EnvJSfile");
Main.processSource(cx, "path/to/your/JQueryJSfile");
cx.evaluateString(global, "your JavaScript", "JavaScript", 1, null);
答案 1 :(得分:0)
不了解Envjs,但为什么要在java中模拟浏览器环境?
第二个问题:
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);
你可以将任何对象放入绑定,地图,列表或pojo中。