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 都需要在接收消息的窗口中添加事件监听器,以接收其他窗口发送的消息。另外,为了安全起见,应该在接收消息时验证消息来源,以防止恶意脚本发送伪造的消息。
网友回复
腾讯混元模型广场里都是混元模型的垂直小模型,如何api调用?
为啥所有的照片分辨率提升工具都会修改照片上的图案细节?
js如何在浏览器中将webm视频的声音分离为单独音频?
微信小程序如何播放第三方域名url的mp4视频?
ai多模态大模型能实时识别视频中的手语为文字吗?
如何远程调试别人的chrome浏览器获取调试信息?
为啥js打开新网页window.open设置窗口宽高无效?
浏览器中js的navigator.mediaDevices.getDisplayMedia屏幕录像无法录制SpeechSynthesisUtterance产生的说话声音?
js中mediaRecorder如何录制window.speechSynthesis声音音频并下载?
python如何直接获取抖音短视频的音频文件url?