Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rhino, adding code from multiple javascript files

I am embedding some javascript in a Java application using Rhino. I am following the example on the Rhino website, executing a script by calling the Context's evaluateString method and passing the actual script in as a String.

I have a whole bunch of existing javascript code that I would like to make use of. I don't want to concatenate it all into an enormous String and pass it in to evaluateString. I would rather be able to load the code in so that I can call it from the code that I do pass into evaluateString (kind of like the AddCode method works in Microsoft's scripting control). I would like to add code like I can currently add variables by using the ScriptableObject.putProperty method.

Is there a way to do this? Can someone provide a code snippet or a link to the documentation. Thanks!

like image 891
Philipp Avatar asked Nov 05 '22 12:11

Philipp


1 Answers

From the documentation and examples it looks like references to previously evaluated objects are controlled by scopes.

Context context = Context.enter();
try {
  ScriptableObject scope = context.initStandardObjects();
  Object out = Context.javaToJS(System.out, scope);
  ScriptableObject.putProperty(scope, "out", out);
  context.evaluateString(scope,
      "function foo() { out.println('Hello, World!'); }", "<1>", 1, null);
  context
      .evaluateString(scope, "function bar() { foo(); }", "<2>", 1, null);
  context.evaluateString(scope, "bar();", "<3>", 1, null);
} finally {
  Context.exit();
}

(Rhino 1.7 release 2)


I know some people use Rhino directly to get the latest version, but the Java 6 implementation can evaluate scripts like this:

ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
engine.eval("function foo() { println('Hello, World!'); }");
engine.eval("function bar() { foo(); }");
engine.eval("bar();");
like image 91
McDowell Avatar answered Nov 12 '22 18:11

McDowell