I have a piece of JS code that I want to execute with a Java object being the global scope. I tried having my Java object extend ScriptableObject and running context.initStandardObjects(this) but no luck (not really sure what I'm doing).
public Foo extends ScriptableObject {
@JSFunction
public int getBar() {
return 42;
}
public void run() {
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects(this);
cx.evaluateString(scope, source, "script", 0, null);
Function fct = (Function) scope.get("run", scope);
fct.call(cx, scope, scope, new Object[0]);
Context.exit();
}
}
While my JS code is:
function run() {
console.log(this.getBar());
}
When running foo.run() however, I get an exception stating that the function getBar() does not exist. Which probably means that Foo is not being set as the global scope.
Can anyone point me in the right direction?
Edit: A more descriptive error message:
org.mozilla.javascript.EcmaError: TypeError: Cannot find function getBar in object [object Foo].