Is there a way to execute a JavaScript function or piece of code in a specific context that it perceives as the global context, without changing the code itself?
For example, if we have the following code:
(function() { x.value = 5; return value; })()
How can we make it work and return 5 without altering the code directly?
I am looking for a solution where the code is executed in the context of variable x, but I am open to other suggestions too.
Update:
The original issue stems from testing a bookmarklet with selenium. The bookmarklet expects to interact with objects on the window, such as:
window.SomeObject = {...}; SomeObject.doSomething();
However, when executing this bookmarklet using $selenium.get_eval, the global object is tied to selenium's own context instead of the window. This means references like SomeObject
don't work as expected.
While I have thought of another potential solution, I would appreciate any insights into the initial question.
Update 2 (solution):
Based on geowa4's response, the final workaround involves the following snippet:
x = {}; with(x) { return (function() { x.value = 5; return value; })(); }