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 都需要在接收消息的窗口中添加事件监听器,以接收其他窗口发送的消息。另外,为了安全起见,应该在接收消息时验证消息来源,以防止恶意脚本发送伪造的消息。
网友回复
如何将自己从小生活的农村村庄做成3d可漫游的高斯泼溅?
同一个iframe多次write包含three的html为啥报错不显示Failed to execute 'write' on 'Document': Identifier 'scene' has a
软件工程师的工作内容将由敲代码转变成使用ai来解决现实世界的问题?
claude skills如何本地自动剪辑生成视频?
物理ai是2026年的趋势吗?
ai能对老相机拍摄的底片进行修复成彩色照片吗?
PlayCanvas能在浏览器中交互展示4dgs高斯泼溅文件吗?
jpeg xl格式图片有啥优势?
glb三维模型有几种方式可以降低体积大小减少精度?
如何使用python PyTorch自己训练一个迷你版本的本地chatgpt聊天机器人?


