Search code examples
javasandboxrhino

Java Rhino allow access to java from safe Context


I want to create sandbox javascript environment and restrict all acces to java classes but the one I specify. I am trying to achieve this by creating Context using Context.initSafeStandardObjects()

Is there a way to allow other classes to be used by javascript? If i create context with Context.initStandardObjects()

I can access all java classes which is not what i want.


Solution

  • I found a solution. You can add an instance of java class into the javascript using:

    Object wrappedTest = Context.javaToJS(test, scope);
    ScriptableObject.putProperty(scope, "test", wrappedTest); //Where text here is name of the variable
    

    Than you can use methods of this class inside javascript, even when u init context using initSafeStandardObjects

    Object result = cx.evaluateString(scope, "test.sampleMethod()", "<cmd>",1, null);
    System.out.println(cx.toString(result));