路径后面的 hash 值可以用来通信。

    思路:

    • a 和 b 是同源的,c 是独立的
    • a 通过 iframe 把 hash 值传递给 c
    • c 通过 iframe 把 hash 值传递给 b
    • 由于 a 和 b 是同源的,所以可以直接修改 a 上的 hash 值,修改为 c 传递给 b 的 hash 值
    1. <iframe src="http://localhost:4000/c.html#aa" frameborder="0"></iframe>
    2. <script>
    3. window.onhashchange = function () {
    4. console.log(location.hash); //=> 通过 onhashchange 监听 hash 变化
    5. }
    6. </script>
    1. <script>
    2. console.log(location.hash); //=> 获取到 a 给的 hash 值
    3. //=> 再通过创建 iframe 标签,把自己要给 a 的 hash 值传递给 b
    4. let iframe = document.createElement('iframe');
    5. iframe.src = 'http://localhost:3000/b.html#bb';
    6. document.body.appendChild(iframe); //=> 一定要把其放到页面中
    7. </script>
    1. <script>
    2. //=> 通过 window.parent.parent 获取到 a 页面,直接修改其 hash 值
    3. window.parent.parent.location.hash = location.hash;
    4. </script>