a 页面可以通过 iframe 和 postMessage 像 b 页面发送信息,其中 a、b 不在同一个域下。

    1. <iframe src="http://localhost:4000/b.html"
    2. frameborder="0"
    3. id="frame"
    4. onload="load()">
    5. </iframe>
    6. <script>
    7. function load() {
    8. let frame = document.getElementById('frame');
    9. //=> 接受两个参数,数据以及传递的地址
    10. frame.contentWindow.postMessage('aa', 'http://localhost:4000/b.html');
    11. }
    12. window.onmessage = function (e) {
    13. console.log(e.data);
    14. }
    15. </script>

    在 iframe 加载完毕之后,向 b 页面发送一个信息。此时需要通过 frame.contentWindow 获取到 b 页面,使用其 postMessage 方法。

    1. <script>
    2. window.onmessage = function (e) {
    3. console.log(e.data);
    4. e.source.postMessage('bb', e.origin);
    5. }
    6. </script>

    b 页面通过 window.onmessage 监听到这个发送过来的数据,通过 e.data 获取数据。

    然后,b 在获取到数据之后,通过 e.source 获取到 a 页面,通过其 postMessage 方法向 a 页面发送信息。

    a 页面中,通过 window.onmessage 监听到这个发送过来的数据,通过 e.data 获取到。

    另外,比较奇怪的是,我测试中接收到两次 b 页面中发送过来的数据,第二次为空