如何将JavaScript代码放在Java程序/应用程序中?

时间:2013-12-20 13:51:06

标签: java javascript

尝试输入Ace Editor的应用程序代码:http://ace.c9.io/#nav=embedding。 我发现了这样的事情:http://metoojava.wordpress.com/2010/06/20/execute-javascript-from-java/ 我把这段代码:

engine.eval(new java.io.FileReader("ace-builds/src-noconflict/ace.js"));

但是我犯了错误。

Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "window" is not defined. (<Unknown source>#1513) in <Unknown source> at line number 1513
    at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:224)
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:249)
    at javaapplication9.JavaApplication9.main(JavaApplication9.java:28)
Caused by: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "window" is not defined. (<Unknown source>#1513)
    at sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3770)
    at sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3748)
    at sun.org.mozilla.javascript.internal.ScriptRuntime.notFoundError(ScriptRuntime.java:3833)
    at sun.org.mozilla.javascript.internal.ScriptRuntime.nameOrFunction(ScriptRuntime.java:1826)
    at sun.org.mozilla.javascript.internal.ScriptRuntime.name(ScriptRuntime.java:1765)
    at sun.org.mozilla.javascript.internal.Interpreter.interpretLoop(Interpreter.java:1785)
    at sun.org.mozilla.javascript.internal.Interpreter.interpret(Interpreter.java:849)
    at sun.org.mozilla.javascript.internal.InterpretedFunction.call(InterpretedFunction.java:162)
    at sun.org.mozilla.javascript.internal.ContextFactory.doTopCall(ContextFactory.java:430)
    at com.sun.script.javascript.RhinoScriptEngine$1.superDoTopCall(RhinoScriptEngine.java:116)
    at com.sun.script.javascript.RhinoScriptEngine$1.doTopCall(RhinoScriptEngine.java:109)
    at sun.org.mozilla.javascript.internal.ScriptRuntime.doTopCall(ScriptRuntime.java:3160)
    at sun.org.mozilla.javascript.internal.InterpretedFunction.exec(InterpretedFunction.java:173)
    at sun.org.mozilla.javascript.internal.Context.evaluateReader(Context.java:1169)
    at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:214)
    ... 2 more

你们中的任何人都知道我该怎么办? 寻求帮助和节日快乐!

1 个答案:

答案 0 :(得分:1)

请记住,您正在脱离上下文执行Javascript文件。

此Javascript文件通常使用浏览器JS引擎执行,因此如果您不在该上下文中,则无法访问某些对象,如导航器,窗口等等。