javascript - 使用 postMessage 的 Iframe 间通信

标签 javascript html iframe browser

我有域 A ( http://example.com) 的父页面

在父页面上存在两个属于同一域但不是域 A 的 iframe。( http://test.com )

当父级是 example.com 时,是否有任何方法可以将一个值从一个 test.com iframe 传递到另一个 iframe,或者是我描述的违反 iframe 的“规则”的行为

谢谢

最佳答案

检查这个 JSFiddle , 我模拟了跨域 iFrame 以使其更具可读性。基本上,两个框架的顶级父级充当调解器,将消息重新分发到目标框架,但框架会触发所有操作和响应。

HTML

<!-- Adding the sandboxing attribute to illustrade cross-domain -->
<iframe id="one" sandbox="allow-scripts"></iframe>
<iframe id="two" sandbox="allow-scripts"></iframe>

JavaScript

var frame_one = document.getElementById('one');
var frame_two = document.getElementById('two');

// The parent has to mediate because cross-domain sandboxing
// is enabled when on different domains, plus backwards compatible.
window.addEventListener('message', function (m) {
    // Using an object with a 'frame' property that maps to the ID
    // which could be done as you would like.
    var targetFrame = document.getElementById(m.data.frame);
    targetFrame.contentWindow.postMessage(m.data.message, '*');
}, false);


/**
 * This is just to illustrate what a normal document would look
 * like you should just set the normal 'src' attribute and the
 * string would be the normal HTML of the documents.
 */
frame_two.srcdoc = '<!DOCTYPE html>\
<html>\
<head>\
<script>\
window.addEventListener("message", function (m) {\
alert("Frame Two Says: " + m.data);\
}, false);\
window.addEventListener("load", function () {\
window.parent.postMessage({frame: "one", message: "Received message from frame two!"}, "*");\
}, false);\
</script>\
</head>\
<body>\
two\
</body>';

frame_one.srcdoc = '<!DOCTYPE html>\
<html>\
<head>\
<script>\
window.addEventListener("message", function (m) {\
alert("Frame One Says: " + m.data);\
}, false);\
window.addEventListener("load", function () {\
setTimeout(function () {\
window.parent.postMessage({frame: "two", message: "Received message from frame one!"}, "*");\
}, 1500);\
}, false);\
</script>\
</head>\
<body>\
one\
</body>';

关于javascript - 使用 postMessage 的 Iframe 间通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20862511/

相关文章:

javascript - 如何在javascript中从链接url获取数据请求?

javascript - 在 Angular ngOptions 中选择时设置所选选项

javascript - 循环操作四个数组

javascript - 如何创建像指标一样的循环进度(饼图)

html - 我的页脚不会位于底部

javascript - 如何防止自动完成选择模糊

javascript - 给定一个整数数组,找到具有最大乘积的一对相邻元素并返回该乘积

javascript - 在网页中显示(语法)树

javascript - 隐藏时停止在后台自动播放Youtube视频

javascript - 如何检测 iframe 的源何时更改?