[英]inter-Iframe communication using postMessage
我有域A的父頁面( http://example.com )
在父頁面上存在兩個相同域但不是域A的iframe。( http://test.com )
當父是example.com時,有沒有辦法將值從一個test.com iframe傳遞給另一個,或者是我對iframe的“規則”描述的行為
謝謝
檢查這個JSFiddle ,我模擬了跨域iFrames,以使其更具可讀性。 基本上,兩個幀的頂級父級充當中介,將消息重新分派到目標幀,但幀會觸發所有操作和響應。
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>';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.