js 监听storage 在当前标签页不生效
时间: 2023-11-30 20:03:14 浏览: 39
在同一个标签页内,如果你在一个窗口中修改了 Storage,那么在同一窗口的其他页面中,通过 Storage API 是无法监听到这个修改的。这是因为 Storage API 只能监听不同窗口之间的数据变化。
如果你需要在同一窗口内监听 Storage 的变化,可以使用 `window.postMessage()` 方法来进行通信。具体方法如下:
1. 在 Storage 变化时,使用 `window.postMessage()` 向当前窗口发送消息,消息内容为 Storage 中的数据。
2. 在当前窗口中添加监听器,监听 `message` 事件。当收到来自同一窗口的消息时,判断消息来源是否为当前窗口,并且消息内容是否为 Storage 中的数据。如果条件满足,则执行相应的操作。
举个例子,假设我们需要监听 `localStorage` 的变化,代码如下:
```js
// 发送消息的函数
function sendStorageUpdateEvent(key, newValue) {
window.postMessage({
type: 'storageUpdate',
key,
newValue
}, window.location.href);
}
// 添加监听器
window.addEventListener('storage', function(event) {
sendStorageUpdateEvent(event.key, event.newValue);
});
// 监听消息
window.addEventListener('message', function(event) {
if (event.source === window && event.data.type === 'storageUpdate') {
// 执行相应的操作
console.log(`Storage ${event.data.key} updated to ${event.data.newValue}`);
}
});
```
在上面的代码中,当 `localStorage` 发生变化时,我们调用了 `sendStorageUpdateEvent` 函数向当前窗口发送消息。同时,我们在当前窗口中添加了 `message` 监听器,当收到来自同一窗口的消息时,我们判断消息是否为 Storage 变化的消息,如果是,则执行相应的操作。