12

如何让两个 iFrame 相互通信?例如,我是第二个 iframe 的元素值,而第一个 iframe 上有显示元素。我需要从第二帧到第一帧的值。我该怎么做?不要说使用cookie,因为大量数据会造成伤害。

4

3 回答 3

24

如果<iframe>元素来自同一个域,那么它们可以直接相互访问。例如,iframe1你可以这样做:

document.getElementById('someDiv').innerHTML = 
    top.document.getElementById('otherIframe').contentWindow.
    document.getElementById('someOtherDiv').innerHTML;
于 2013-05-20T20:06:02.673 回答
5

我会首先警告您,您将需要两个 iframe 的完整代码修改能力。iframe 受到严格的安全处理;否则,我可以创建一个域“bunkofamerica.com”,将“bankofamerica.com”放在 iframe 中,然后在用户输入密码时对其进行分析。(无论如何,银行往往都有破坏 iframe 的代码,但仍然......)

您正在寻找这个本机功能: https ://developer.mozilla.org/en-US/docs/Web/API/window.postMessage

这是我公司用来使这个更跨浏览器兼容的 github 库:https ://github.com/daepark/postmessage

jbabey 是正确的,如果 iframe 在同一个域和协议中,那就更容易了。

Opera Docs 用最相关的例子解释了这一点https://dev.opera.com/articles/window-postmessage-messagechannel/#channel

于 2013-05-20T20:08:21.380 回答
0

首先,框架可以在其自身之外进行交互的唯一方法是,如果在两个地方加载的内容来自同一个域,否则您将收到 CORS 错误。

假设这一切都是肉汁,我会在父框架的窗口对象上创建一个管理器对象。

window.Mgmt = {
    frame1: $('iframe#frame1'),
    frame2: $('iframe#frame2')
}

然后在任一 iframe 中,您应该能够使用window.parent.Mgmt.frame1等访问该对象

于 2013-05-20T20:09:27.913 回答