JSBձոգչ
JSBձոգչ

Reputation: 41378

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.

Upvotes: 1

Views: 154

Answers (3)

user4876141
user4876141

Reputation:

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();

Upvotes: 0

jbabey
jbabey

Reputation: 46647

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.

Upvotes: 1

Robusto
Robusto

Reputation: 31883

Replace window with top if you're calling a function that exists in the global scope of the parent page.

Upvotes: 0

Related Questions