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 都需要在接收消息的窗口中添加事件监听器,以接收其他窗口发送的消息。另外,为了安全起见,应该在接收消息时验证消息来源,以防止恶意脚本发送伪造的消息。
网友回复
gpt-image2能直接将图片转成分层透明的psd设计文件?
claude code、codex、gemini cli如何切换国内大模型使用?
蒸馏最强ai大模型是中小ai模型低成本升级的最好通道?
arena.ai上为啥没有最新的claude4.7及gpt5.5呢?
ai大模型公司为啥开始大量招聘文科生了?
cloudflared如何在低版本centos6或7上安装?
bfwsoa框架如何开启异步缓存与异步任务模式?
selenium如何获取网页js加载渲染后的真实dom结构?
go编写的Eino与python编写的langchain如何选择?
LangChain如何编写多个agent协同工作的代码?


