localStorage变动监听
fanzheming 2020-01-09
js
Vue
# 单页面监听localStorage变动
方法1:重写localStorage.setItem()方法
const oldSetItem = window.localStorage.setItem window.localStorage.setItem = function(key, newValue) { if (key === '你要监听的key') { // do something } oldSetItem(key, newValue) }
1
2
3
4
5
6
7方法2:封装原生localStorage的api,生成自己的自定义功能
var myStorage = { setItem(key, val, ...rest){ // do something window.localStorage.setItem(key,val) } getItem(key,..rest){ // do something return window.localStorage. getItem(key) } // ...其他方法 } export default myStorage
1
2
3
4
5
6
7
8
9
10
11
12方法3:监听localStorage时间
// 重写setItem方法 const oldSetItem = window.localStorage.setItem window.localStorage.setItem = function(key, newValue) { var setItemEvent = new Event("setItemEvent") setItemEvent.key = key setItemEvent.newValue = newValue window.dispatchEvent(setItemEvent) oldSetItem.apply(this, arguments) } // 添加监听事件 window.addEventListener("setItemEvent", function(e) { // do something })
1
2
3
4
5
6
7
8
9
10
11
12
13
# 不同页面监听localStorage变动
window.addEventListener("storage", function (e) {
if (e.key === '你要监听的key') {
// do something
console.log(e.newValue)
}
})
1
2
3
4
5
6
2
3
4
5
6