Playing around with the Nashorn JavaScript engine

public TestScriptExecutor() {
ScriptEngineManager engineManager = new ScriptEngineManager();
engine = (NashornScriptEngine)
engineManager.getEngineByName("nashorn");
}
public void loadScript(String script) {
Bindings bindings =
engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("ui", this);
try {
engine.compile(script).eval(bindings);
} catch (ScriptException e) {
LOG.warn("scripterror: ", e);
}
}
public void invokeScriptFunction(String functionName) {
try {
LOG.info("trying to run: {}", functionName);
engine.invokeFunction(functionName);
} catch (ScriptException e) {
LOG.warn("script error!");
} catch (NoSuchMethodException e) {
LOG.info("method not defined");
}
}
// setting up variables for JS did NOT work like this:
final SimpleScriptContext context = new SimpleScriptContext();
context.setAttribute("ui", this, ScriptContext.ENGINE_SCOPE);
engine.setContext(context);
engine.compile(script).eval(context);
// ... call a function, the ui variable was not bound inside the
// js code then

--

--

Software engineer from Austria. Passionate about software, likes photography, addicted to podcasts and always busy. http://paukl.at

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Paul Klingelhuber

Paul Klingelhuber

Software engineer from Austria. Passionate about software, likes photography, addicted to podcasts and always busy. http://paukl.at