15

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).

gyre
  • 16,369
  • 3
  • 37
  • 47
fejesjoco
  • 11,763
  • 3
  • 35
  • 65

3 Answers3

11

How 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>
gyre
  • 16,369
  • 3
  • 37
  • 47
4

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();
The Moisrex
  • 1,857
  • 1
  • 14
  • 16
4

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).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375