Skip to content

Instantly share code, notes, and snippets.

@irace
Created July 29, 2011 01:18
Show Gist options
  • Save irace/1112944 to your computer and use it in GitHub Desktop.
Save irace/1112944 to your computer and use it in GitHub Desktop.
Invoke JavaScript from Java, using Mozilla Rhino
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.tools.shell.Global;
import org.mozilla.javascript.tools.shell.Main;
public class ScriptTest {
public static void main(String[] args) {
final Context cx = ContextFactory.getGlobal().enterContext();
cx.setOptimizationLevel(-1);
cx.setLanguageVersion(Context.VERSION_1_5);
final Global global = Main.getGlobal();
global.init(cx);
final Scriptable scope = cx.initStandardObjects(global);
Main.processSource(cx, "/Users/Bryan/Programming/Libraries/thatcher-env-js-cb738b9/dist/env.rhino.js");
Main.processSource(cx, "/Users/Bryan/Programming/Libraries/jquery-1.4.2.min.js");
final String script =
"window.location = 'test.html';" +
"var text = $('p:first').text();";
cx.evaluateString(scope, script, "", 1, null);
System.out.println("Text: " + scope.get("text", scope));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment