Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

localStorage 变化监听及自定义事件 #53

Open
lovelmh13 opened this issue Apr 20, 2021 · 0 comments
Open

localStorage 变化监听及自定义事件 #53

lovelmh13 opened this issue Apr 20, 2021 · 0 comments

Comments

@lovelmh13
Copy link
Owner

WindowEventHandlers.onstorage

window.addEventListener('storage', function(e) {
  document.querySelector('.my-key').textContent = e.key;
  document.querySelector('.my-old').textContent = e.oldValue;
  document.querySelector('.my-new').textContent = e.newValue;
  document.querySelector('.my-url').textContent = e.url;
  document.querySelector('.my-storage').textContent = e.storageArea;
});

但是 有个前提:必须是同源的不同页面才会触发。

比如如果是同源的页面,不同的 tab ,可以触发。如果写的都是现在的 SPA 项目,同一个 tab,不管怎么切换页面(路由),都不会触发。

但是也有解决办法——自定义事件。

自定义事件

通过自定义事件(本质就是发布订阅),在 setItem 的时候去发布一个事件。提前订阅的事件的回掉就会触发。

这里用 AOP 实现在 setItem 时,定义一个事件。

// 订阅
window.addEventListener('setItemEvent', function (e) {
  if (e.key === 'shop_id') {
	// ...
  }
})

// 切片,发布
const orignalSetItem = window.localStorage.setItem
window.localStorage.setItem = function (key, content) {
   const setItemEvent = new Event('setItemEvent')
   setItemEvent.newValue = content
   setItemEvent.key = key
   window.dispatchEvent(setItemEvent)
   orignalSetItem.apply(this, arguments)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant