LocalStorage / SessionStorage
LocalStorage 和 SessionStorage 是浏览器提供的本地存储机制,可以在不同的浏览器窗口之间共享数据。当一个窗口修改了存储的值时,其他窗口会触发 storage 事件,可以通过该事件接收到其他窗口的数据。// 发送消息
localStorage.setItem('message', 'hello');
// 接收消息
window.addEventListener('storage', function(event) {
if (event.key === 'message') {
console.log(event.newValue); // 'hello'
}
});
BroadcastChannel
BroadcastChannel 是一个跨窗口通信 API,可以在不同的浏览器窗口之间发送和接收消息。当一个窗口发送消息时,其他窗口会触发 message 事件,可以通过该事件接收到其他窗口的数据。// 发送消息
const channel = new BroadcastChannel('my-channel');
channel.postMessage('hello');
// 接收消息
const channel = new BroadcastChannel('my-channel');
channel.addEventListener('message', function(event) {
console.log(event.data); //'hello'
});
Window.postMessage
Window.postMessage 是一个跨文档通信 API,可以在不同的浏览器窗口或 iframe 之间发送和接收消息。当一个窗口发送消息时,其他窗口会触发 message 事件,可以通过该事件接收到其他窗口的数据。// 发送消息
otherWindow.postMessage('hello', 'https://example.com');
// 接收消息
window.addEventListener('message', function(event) {
if (event.origin === 'https://example.com') {
console.log(event.data); // 'hello'
}
});
需要注意的是,Window.postMessage 和 BroadcastChannel 都需要在接收消息的窗口中添加事件监听器,以接收其他窗口发送的消息。另外,为了安全起见,应该在接收消息时验证消息来源,以防止恶意脚本发送伪造的消息。
网友回复