Window:storage 事件
当与当前窗口共享同一存储区域(localStorage 或 sessionStorage)的另一文档更新该存储区域时,Window 接口的 storage 事件便会触发。该事件不会在做出更改的窗口上触发。
- 对于
localStorage,该事件会在与发起文档同源的所有其他浏览上下文中触发。这包括同源的其他标签页。 - 对于
sessionStorage,该事件会在与发起文档同源且处于同一顶级浏览上下文中的所有其他浏览上下文中触发。这只包括同一标签页中的嵌入式 iframe(如果有的话),不包括其他标签页。
此事件不可取消,也不会冒泡。
语法
在诸如 addEventListener() 之类的方法中使用事件名称,或设置事件处理程序属性。
js
addEventListener("storage", (event) => { })
onstorage = (event) => { }
事件类型
一个 StorageEvent。继承自 Event。
事件属性
事件处理程序别名
除了 Window 接口,事件处理程序属性 onstorage 也可在以下目标上使用
示例
当 storage 事件触发时,将 sampleList 项记录到控制台
js
window.addEventListener("storage", () => {
// When local storage changes, dump the list to
// the console.
console.log(JSON.parse(window.localStorage.getItem("sampleList")));
});
使用 onstorage 事件处理程序属性可以实现相同的操作
js
window.onstorage = () => {
// When local storage changes, dump the list to
// the console.
console.log(JSON.parse(window.localStorage.getItem("sampleList")));
};
规范
| 规范 |
|---|
| HTML # event-storage |
| HTML # handler-window-onstorage |
浏览器兼容性
加载中…