listen to localstorage changes code example
Example 1: js listen localstorage change
var originalSetItem = localStorage.setItem;
localStorage.setItem = function(key, value) {
var event = new Event('itemInserted');
event.value = value;
event.key = key;
document.dispatchEvent(event);
originalSetItem.apply(this, arguments);
};
var localStorageSetHandler = function(e) {
alert('localStorage.set("' + e.key + '", "' + e.value + '") was called');
};
document.addEventListener("itemInserted", localStorageSetHandler, false);
localStorage.setItem('foo', 'bar');
Example 2: listen to localstorage changes
window.addEventListener('storage', () => {
console.log(JSON.parse(window.localStorage.getItem('sampleList')));
});
Example 3: listen to localstorage changes
var originalSetItem = localStorage.setItem;
localStorage.setItem = function(){
document.createEvent('Event').initEvent('itemInserted', true, true);
originalSetItem.apply(this, arguments);
}