I'm using Rhino 1.7R4 and env.js 1.2 to run Javascript code inside Java
I want to print from my Javascript code a string to the Java console.
According to: http://evilroundabout.blogspot.com.au/2009/11/javascript-printing-rhino.html
I should use: print("Hello world");
but when I do I get:
org.mozilla.javascript.EcmaError: ReferenceError: "print" is not defined. (svg-renderer-highcharts-2.1.4.js#20)
at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3687)
at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3665)
at org.mozilla.javascript.ScriptRuntime.notFoundError(ScriptRuntime.java:3750)
at org.mozilla.javascript.ScriptRuntime.nameOrFunction(ScriptRuntime.java:1794)
at org.mozilla.javascript.ScriptRuntime.getNameFunctionAndThis(ScriptRuntime.java:2188)
at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:1308)
at script.renderSVGFromObject(svg-renderer-highcharts-2.1.4.js:20)
If I use document.write I don't see any output.
You can use the same scope that the rhino shell uses quite easily. The rhino shell relies on a specially constructed scope instance called Global which defines several functions like "print". The sample below demonstrates how to use Global and the "print" function. This will print "Hello World!" twice to stdout.
import org.mozilla.javascript.Context;
import org.mozilla.javascript.tools.shell.Global;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
Context cx = Context.enter();
Global global = new Global(cx);
cx.evaluateString(global, "print('Hello World!')",
"helloWorld.js", 1, null);
Context.exit();
}
}
I discovered this through experimentation after digging through the Rhino shell executable.
And for the sake of completeness here are the other global functions defined by Global:
"defineClass",
"deserialize",
"doctest",
"gc",
"help",
"load",
"loadClass",
"print",
"quit",
"readFile",
"readUrl",
"runCommand",
"seal",
"serialize",
"spawn",
"sync",
"toint32",
"version"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With