a 页面可以通过 iframe 和 postMessage 像 b 页面发送信息,其中 a、b 不在同一个域下。
<iframe src="http://localhost:4000/b.html"
frameborder="0"
id="frame"
onload="load()">
</iframe>
<script>
function load() {
let frame = document.getElementById('frame');
//=> 接受两个参数,数据以及传递的地址
frame.contentWindow.postMessage('aa', 'http://localhost:4000/b.html');
}
window.onmessage = function (e) {
console.log(e.data);
}
</script>
在 iframe 加载完毕之后,向 b 页面发送一个信息。此时需要通过 frame.contentWindow
获取到 b 页面,使用其 postMessage 方法。
<script>
window.onmessage = function (e) {
console.log(e.data);
e.source.postMessage('bb', e.origin);
}
</script>
b 页面通过 window.onmessage
监听到这个发送过来的数据,通过 e.data
获取数据。
然后,b 在获取到数据之后,通过 e.source
获取到 a 页面,通过其 postMessage 方法向 a 页面发送信息。
a 页面中,通过 window.onmessage
监听到这个发送过来的数据,通过 e.data
获取到。
另外,比较奇怪的是,我测试中接收到两次 b 页面中发送过来的数据,第二次为空