views:

41

answers:

3

I have an html page where I have this layout essentially:

<html>
<body>

<!-- iFrame A -->
<iframe></iframe>

<!-- iFrame B -->
<iframe></iframe>
</body>
</html>

In IFRAME "B", I'd like to call a js function in IFRAME "A", which will ultimately change the window.location property and redirect the page. I have jquery at my disposal as well, but have been unable to figure out a way of calling something in that adjacent frame.

Any suggestions?

A: 

Use window.parent to get the parent (the main window) then use window.frames on the parent window to get frame B. From there call your function.

stevebot
In some browsers, the window.frames array is only populated if the frames are named, rather than having only an ID
mplungjan
+1  A: 

Assuming everything is on the same domain, and you have two iframes with ids "iframe-a" and "iframe-b", with jQuery in the parent:

In frame A:

function foo() {
  alert("foo from frame A");
}

From frame b:

window.parent.$("#iframe-a")[0].contentWindow.foo();

And you should see "foo from frame A" get alerted.

bcherry
why [0] ? and why parent? window.$("#iframeA").contentWindow.foo();should be enough assuming id="iframeA" since you should always have unique IDs
mplungjan
I'm not sure why that works, but it does. I'll have to research this some more. Thanks for your insights @bcherry
mirezus
@mplungjan - Since we're in frame B, we have to traverse up to the parent before we can query for frame A, since it is not part of B's DOM. The `[0]` gets the raw DOM node from the jQuery object, so we can access `contentWindow`.
bcherry
@mirezus - the `contentWindow` property on an iframe is the "global object" for that iframe. Within the iframe, it's just called `window`. Hope that helps.
bcherry
Hmm, I cannot seem to get it to show now, but I remembered when the iframe could access the parent window it was in using window. and not needing parent. which was needed in real frames
mplungjan
+1  A: 

In some browsers, the window.frames array is only populated if the frames are named, rather than having only an ID If the frames are named and the content are from the same origin (domain, port, protocol), then window.frameb.functionName() will trigger the function in standard javascript. See other answer(s) for jQuery version

mplungjan