使用postMessage进行iframe间通信

时间:2013-12-31 19:45:47

标签: javascript html5 iframe browser

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

在父网页上存在两个属于同一个域而非域A的iframe。(http://test.com

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

由于

1 个答案:

答案 0 :(得分:6)

结帐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>';