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 都需要在接收消息的窗口中添加事件监听器,以接收其他窗口发送的消息。另外,为了安全起见,应该在接收消息时验证消息来源,以防止恶意脚本发送伪造的消息。
网友回复
python能写一个检测nginx rewrite高危漏洞的工具代码?
css如何给video视频进行mask遮罩?
windows如何同时允许两个用户远程桌面连接同一个电脑?
nginx升级到1.30.1导致无法启动 [emerg] SSL_CTX_new() failed怎么办?
什么是ASLR(地址随机化)?
有没有不依赖embedding向量的RAG技术?
有没有支持实时打断语音通话并后台帮你执行任何的ai模型?
开源ai大模型文件格式GGUF、MLX、Safetensors、 ONNX 有什么区别?
出海挣钱支付收款PayPal、Wise 、PingPong、Stripe如何选择?
如何实现类似google的图片隐形水印添加和识别技术?


