0

Context.javaToJS seems to just pass java.lang.Strings straight through.

I am sandboxing the JavaScript (according to http://codeutopia.net/blog/2009/01/02/sandboxing-rhino-in-java/) so java.lang.String is not useable in JavaScript unless I punch holes through the ClassShutter (which I would rather not do).

Am I missing something obvious?

1 Answer 1

1

Try this:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
ScriptContext context = engine.getContext();
context.setAttribute("jsString", "I am Java String", ScriptContext.ENGINE_SCOPE);
context.setAttribute("jsBoolean", true, ScriptContext.ENGINE_SCOPE);
context.setAttribute("jsNumber",  123456, ScriptContext.ENGINE_SCOPE);
engine.eval("function getValueAndType(obj){return obj + ' - ' + typeof obj;}");
Assert.assertEquals("Something wen wrong", "I am Java String - string", engine.eval("getValueAndType(jsString)"));
Assert.assertEquals("Something wen wrong", "true - boolean", engine.eval("getValueAndType(jsBoolean)"));
Assert.assertEquals("Something wen wrong", "123456 - number", engine.eval("getValueAndType(jsNumber)"));
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, the setAttributes seems to create js strings, while Context.javaToJS just passes through Java strings. I suppose that I could fudge things that way. But ideally would like returned values. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.