通信方式有两种:监听localStorage和postMessage
1、监听localStorage:
JavaScript原生就有一个监听localStorage变化的事件storageEvent,当同一域下不同页面修改storage会触发storageEvent事件,自己修改storage则不会触发。
window.addEventListener('storage', e => {
console.log(e.newValue)
})
2、postMessage:
窗口window对象提供的postMessage方法和message事件实现跨页面通信。
otherWindow.postMessage(message, targetOrigin, [transfer])
window.addEventListener('message', function (e) {
console.log('message:',e)
})
otherWindow:其他窗口的一个引用,比如 iframe 的 contentWindow 属性、执行 window.open 返回的窗口对象、或者是命名过或数值索引的 window.frames。
message:将要发送到其他 window的数据。
targetOrigin:指定哪些窗口能接收到消息事件,其值可以是 *(表示无限制)或者一个 URI。
transfer:可选,是一串和 message 同时传递的 Transferable 对象。这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。
otherWindow获取方式:
otherWindow = window.open(url) 获取新打开页面的 Window 对象的引用
otherWindow = window.opener 获取对创建该窗口的 Window 对象的引用