【KO】前端面试六
以下继续为你解答剩余题目:
109. 不同标签页或窗口间的【主动推送消息机制】的方式有哪些?(不借助服务端 )
localStorage
+storage
事件:- 原理:一个标签页修改
localStorage
,其他同域标签页会触发storage
事件。 - 用法:
- 原理:一个标签页修改
// 发送方
localStorage.setItem('cross-tab-msg', JSON.stringify({ type: 'notice', data: '新消息' })); // 接收方
window.addEventListener('storage', (event) => {if (event.key === 'cross-tab-msg') {const msg = JSON.parse(event.newValue);console.log('收到跨页消息:', msg);}
});
BroadcastChannel
API:- 原理:创建同名称的广播通道,不同标签页/窗口通过通道收发消息,浏览器原生支持的跨页通信方案。
- 用法:
// 发送方
const channel = new BroadcastChannel('my-channel');
channel.postMessage({ type: 'update', content: '数据变更' }); // 接收方
const channel = new BroadcastChannel('my-channel');
channel.addEventListener(