gpt4 book ai didi

javascript - 使用 postMessage 的 Iframe 间通信

转载 作者:太空狗 更新时间:2023-10-29 15:01:26 26 4
gpt4 key购买 nike

我有域 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com