Search code examples
javajava-8nashornscriptengine

How to add arguments with the ScriptEngineManager method getEngineByName("nashorn")?


I am using Nashorn with Java API 8. I would like to secure javascript execution to be sure the code can't call Java package.

It is possible as follow :

NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine("-strict", "--no-java", "--no-syntax-extensions");

However, using NashornScriptEngineFactory directly is not really nice.

The good way is to use the ScriptEngineManager. The NashornScriptEngineFactory is the factory used by ScriptEngineManager to make an instance of ScriptEngine. It is explained in this documentation :

This package provides the javax.script integration, which is the preferred way to use Nashorn. You will ordinarily do this to obtain an instance of a Nashorn script engine:

import javax.script.*;
...
ScriptEngine nashornEngine = new ScriptEngineManager().getEngineByName("Nashorn");

I did not found a solution to create a ScriptEngine using ScriptEngineManager with the ability to give some extra arguments like "-strict", "--no-java", "--no-syntax-extensions".

can anyone help me in this matter ? Thank you in advance.


Solution

  • Well, javax.script is generic API to be used against any scripting language implementation. As designed, the API does not provide for "engine configuration options" at all!

    What is the exact problem with using Nashorn specific API? Do you feel that you're using engine specific API? But then you're using engine specific options - which won't be supported by other engines. So, you're tied to a specific engine implementation anyway.

    There is another system property way to specifying Nashorn options. You can define System property "nashorn.args". This property is process wide and so will be used by all Nashorn engines created in your Java process.

    See also: https://wiki.openjdk.java.net/display/Nashorn/Nashorn+jsr223+engine+notes