简体   繁体   中英

How to call javascript function inside an adjacent iframe

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?

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.

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

使用window.parent获取父窗口(主窗口),然后在父窗口上使用window.frames获取帧B。从那里调用函数。

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