localStorage变动监听

1/9/2020 jsVue

# 单页面监听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

# 参考链接

Last Updated: 4/8/2020, 8:05:45 PM
不喜欢下雨天Remix
Piggy,Owen,DP龙猪