Let's say there's a function in the top window. For example:
function z() { alert(window.name); }
Let's also say there's an iframe in this document (same origin).
Can a function in the top window execute this function in the context of another window, such that it displays the name of the iframe and not the top window?
In other words, how is the global object bound to a function and can it be changed?
Naive attempt that doesn't work: / (displays top for both invocations).
Let's say there's a function in the top window. For example:
function z() { alert(window.name); }
Let's also say there's an iframe in this document (same origin).
Can a function in the top window execute this function in the context of another window, such that it displays the name of the iframe and not the top window?
In other words, how is the global object bound to a function and can it be changed?
Naive attempt that doesn't work: https://jsfiddle.net/wos2o3gx/ (displays top for both invocations).
Share Improve this question edited Mar 26, 2017 at 13:17 gyre 16.8k4 gold badges40 silver badges47 bronze badges asked Mar 26, 2017 at 10:31 fejesjocofejesjoco 11.9k4 gold badges38 silver badges65 bronze badges3 Answers
Reset to default 11How is the global object bound to a function and can it be changed?
A function's global context is determined at the time the function is created, and does not change even when you make that function a property of another window
context. There are dynamic alternatives, like substituting window
with this
, but since this
isn't always set to the global object (for example in strict mode), I would suggest passing a window
variable to your function instead:
Demo Snippet (JSFiddle):
function z (window) {
window = window || self
console.log(window.name)
}
window.name = 'w top'
z()
var iframe = document.getElementById('iframe')
iframe.contentWindow.name = 'w iframe'
z(iframe.contentWindow)
<iframe id="iframe" src="about:blank" name="w iframe">
</iframe>
how is the global object bound to a function?
By closure.
and can it be changed?
No. You'd need to create a new function, in the context of the other window (e.g. by using its eval
or Function
constructor).
you can use this
instead of window
in your example, like this:
function z() {
alert(this.name);
}
window.name = 'w top';
z();
var iframe = document.getElementById('iframe');
frame.contentWindow.name = 'w iframe';
frame.contentWindow.z = z;
frame.contentWindow.z();