简体   繁体   中英

Invoke JS function in IFrame window

I have a JS function which I sometimes want to invoke in the context of the main window, and sometimes in the client window. Something like the following:

var f = function() { alert(window.location); };

f(); // should show the location of the parent frame

// DOESN'T WORK, but is intended to show the location of the first IFrame
f.call(window.frames[0]);

Googling this mostly shows me how to invoke a function which is defined in the child frame. I, however, want to take a function which is defined in the parent and execute it in the child frame. And, to eliminate the obvious, adding a window parameter to the function is not a viable option.

If you want to execute a function defined in a parent window but in the context of your window, you can use apply :

top.someFunction.apply(window);

The two windows must be in the same domain for this to work.

如果要调用父页面的全局范围内存在的函数,请用top替换window

Have you tried something like the following:

// reference to window in iframe with id or name 'myIframe'
var win = window.frames['myIframe'];

// invoke function in win
win.getEvents();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM