最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Execute a function within the context of a different window? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a comment  | 

3 Answers 3

Reset to default 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>

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();
发布评论

评论列表(0)

  1. 暂无评论