s hogg
s hogg

Reputation: 121

Accessing/Intercepting Nashorn's Global Object Variables

This is along the same lines as the question titled "Capturing Nashorn's Global Variables". I'm finding it very limiting not being able to intercept the assignment of variables to the global object.

For instance, say I eval the script "a = 10". Perhaps I want to call a listener to notify something that 'a' was added to the scope. The only way I could do this is to investigate the global object after the script is eval'd.

Or say i want to intercept an object being assigned to the global scope and substitute it for another; if it was using Bindings I could implement put, and delegate off to some other bindings:

public Object put(String name, Object value) {
    //put a toStringed version of the object in scope
    return delegate.put(name, value+"");
}

This way, when the code 'a=10' is evalled, it would put "10" in scope instead of 10.

It's handy having a Bindings interface to implement, but frustrating that I can't provide something like this implementation for the global object. ScriptObjectMirror is final, so I can't even overload this and hijack the subsequent call to the internal ScriptObject. Am I missing something?

Upvotes: 12

Views: 542

Answers (1)

Stijn de Witt
Stijn de Witt

Reputation: 42095

So basically what you want to do is to intercept/trap assignments to arbitrary properties on some object. In your case, the global object.

Afaik, this was never really possible without some pretty hacky code indeed. A search for 'observables javascript' might help you with that, but be warned that you'll get into some muddy territory.

If this is meant for testing (as opposed to production code), a setTimeout / setInterval with some listener that periodically enumerates all properties of the global object and logs a warning if one was added might be good enough for you.

In the future, we'll have the Javascript Proxy standard to help us with this but I seriously doubt it is there yet in Nashorn. It's been a while since I worked with Nashorn but after the initial burst on the scene it has been quiet on the Nashorn front afaict...

Upvotes: 0

Related Questions