浏览器跨页面通信

通信方式有两种:监听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 对象的引用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值