监听localStorage,重写了setItem

技术记录分享

const setItem = localStorage.setItem
localStorage.setItem = function (name, value){
  setItem.apply(this, arguments)
  var event = new Event('setItem')
  event.key = name
  event.value = value
  window.dispatchEvent(event);
}
// 页面使用
window.addEventListener('setItem', function (e) { 
  console.log(e);
})

setInterval(()=> {
  localStorage.setItem('aaa', JSON.stringify({a: Math.random()}))
}, 3000)

你可能感兴趣的:(javascript前端)