Including a JavaScript file during Rhino eval

浪尽此生 提交于 2019-12-01 07:06:28

问题


How would one include a script "Bar" from within another script "Foo" that is being evaluated by the Rhino Engine, running in Java.

IE, setup the script engine like this in Java:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
BufferedReader br = new BufferedReader(new FileReader(new File("Foo.js")));
engine.eval(br);

... and put the following in Foo:

load(["Bar.js"])

According to Rhino shell documentation, that's the way to do it. But when running from Java, it's clearly not implemented:

javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "load" is not defined.

@Phillip:

Thanks for the creative response. Your solution as is doesn't quite work because eval doesn't make the parsed function available unless the Invocable interface is used. Further, it doesn't work in cases where the Java code is not accessible. I elaborated on your workaround and created something that will work in pure JS:

First create an engine, exposing the Invocable interface:

var engine = new Packages.javax.script.ScriptEngineManager().getEngineByName("javascript");
engine = Packages.javax.script.Invocable(engine);

Then "load()" the script(s)

engine.eval(new java.io.FileReader('./function.js'));

At this point, functions can be evaluated with:

engine.invokeFunction("printHello", null);

回答1:


I managed to do it by passing the engine to itself and then calling eval() on it inside the Javascript code:

Java code:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.put("engine", engine);
engine.eval(new FileReader("test.js"));

test.js:

engine.eval(new java.io.FileReader('function.js'));
printHello();

function.js:

function printHello() {
    print('Hello World!');
}

output:

Hello World!

I don't know if that's the most elegant way to do it, but it works.



来源:https://stackoverflow.com/questions/12357334/including-a-javascript-file-during-rhino-eval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!