0

I am executing a third party javascript file in the RhinoScriptEngine. The file contains references to methods in "this". i.e. this.getField. The file is written with the expectation that "this" is some object other than the js Window object. So now when I run the script I'm getting this error:

Cannot find function getField in object [object Global]

Using the Java ScriptEngine (Rhino), how can I change the object "this" is referring to? Thanks!

Generally, I can call something like, scriptEngine.eval(script). This works great as long as there are no references to some global "this" object. I'd like to do something similar, but where I can define what "this" is.

Amber
  • 2,413
  • 1
  • 15
  • 20
  • In web browsers, there's `.call`, not sure if it's the same in Rhino. – gen_Eric Apr 10 '12 at 15:32
  • 1
    Does [this answer](http://stackoverflow.com/a/6709811/1106925) help? –  Apr 10 '12 at 17:05
  • 1
    possible duplicate of [Rhino: How to pass Java object to script, where can be referenced as "this"](http://stackoverflow.com/questions/6709542/rhino-how-to-pass-java-object-to-script-where-can-be-referenced-as-this) –  Apr 10 '12 at 18:24
  • It is similar to the possible duplicate above, but the solution that is closest to what I was looking for is this: http://stackoverflow.com/a/2554033/1324406. Thanks for your help! – Amber Apr 10 '12 at 22:00

1 Answers1

1

I know this answer is over 3 years later, but if anyone finds their way to this page looking for a solution the following code worked for me:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript"); //Your Engine Name
engine.put("this", theObject);

Now referencing this will access the desired object.

Jaggler3
  • 304
  • 4
  • 10
  • Doesn't work for me (Java 8). `engine.eval("this");` always yields `[object global]`. I'm afraid it can't be done. – Neal Ehardt Feb 13 '17 at 18:20