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