Listen / Observe - changes in LocalStorage using store.js

岁酱吖の 提交于 2020-06-28 02:40:31

问题


I am using store.js (A JS library) to manage local storage.

What I am trying to do

Save value of client in localStorage in one tab of the browser and then when the value changes, I want to listen to the value changed.

Problem

The below code works in the same tab of the browser, but when I check another tab, there is no change event triggered.

store.set('client', {
  'name': Math.random()
});

$('#mybtn1').click(function() {
  store.set('client', {
    'name': Math.random()
  });
});


store.observe('client', function(val, oldVal) {
  console.log('changed');
  console.log(store.get('client'));
});
<script src="https://raw.githubusercontent.com/marcuswestin/store.js/master/dist/store.everything.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="mybtn1" type="button">click</button>

Help

Can you please guide on what I am going wrong. I am also open to using Jquery for these changes listening.


回答1:


I had a similar issue with store.js so I end up using pure localStorage and event listener approach to implement the problem.

Here is the working JSFiddle: Detect localStorage change on another browser tab

Explanation:

This makes use of Web Storage API.

You can create new localStorage key-value pair using a call to,

localStorage.setItem("current_tenant", "Tenant1");

Now whenever this storage is changed, StorageEvent is fired. This event is only sent to other windows.

The StorageEvent is fired whenever a change is made to the Storage object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects. Source: MDN Web Docs

You can then add event listener on this storage and detect changes using event properties, oldValue and newValue Eg,

Converted your example into JSFiddle and here is the solution that combines both storeJS and StorageEvent



来源:https://stackoverflow.com/questions/50580689/listen-observe-changes-in-localstorage-using-store-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!