Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example of how to call functions from a JavaScript snippet running inside the Java8 Nashorn engine
function testMe() {
ui.showMessage('this should show up in the UI this is running in');
[main] INFO a.p.d.blogpost.TestScriptExecutor - trying to run: testMe
[main] INFO a.p.d.blogpost.TestScriptExecutor - showMessage called: this should show up in the UI this is running in
package at.paukl.dynclient.blogpost;
import jdk.nashorn.api.scripting.NashornScriptEngine;
import org.slf4j.Logger;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import static org.slf4j.LoggerFactory.getLogger;
* @author Paul Klingelhuber
public class TestScriptExecutor {
private static final Logger LOG = getLogger(TestScriptExecutor.class);
private NashornScriptEngine engine;
public static void main(String[] args) throws Exception {
final TestScriptExecutor test = new TestScriptExecutor();
test.loadScript(IOUtils.toString(new FileReader("exampleScript.js")));
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 {
} catch (ScriptException e) {
LOG.warn("scripterror: ", e);
public void invokeScriptFunction(String functionName) {
try {"trying to run: {}", functionName);
} catch (ScriptException e) {
LOG.warn("script error!");
} catch (NoSuchMethodException e) {"method not defined");
public void showMessage(String message) {"showMessage called: {}", message);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment