I want to listen for changes that are happening in the localStorage API on the same page (Not in multiple tabs like the spec says).
I am currently using this code:
var storageHandler = function () {
alert('storage event 1');
};
window.addEventListener("storage", storageHandler, false);
localStorage.setItem('foo', 'bar');
Does anyone know a vanilla JavaScript way to listen to events on localStorage on one page (no jQuery)
The main features of localStorage are: Shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.
Limitations & considerations to use local storage: It is not secure, can be accessed by browser developer tools, so don't use it to store sensitive data. It can be cleared by the user when he/she clears all browser history. It can only store string data.
LocalStorage is synchronous, each local storage operation you run will be one-at-a-time. For complex applications this is a big no-no as it'll slow down your app's runtime.
Since JS is dynamical language just rewrite original functions.
var originalSetItem = localStorage.setItem;
localStorage.setItem = function(){
document.createEvent('Event').initEvent('itemInserted', true, true);
originalSetItem.apply(this, arguments);
}
Updated above answer, as document.createEvent now is part of an old, deprecated API.
const originalSetItem = localStorage.setItem;
localStorage.setItem = function(key, value) {
const event = new Event('itemInserted');
event.value = value; // Optional..
event.key = key; // Optional..
document.dispatchEvent(event);
originalSetItem.apply(this, arguments);
};
const localStorageSetHandler = function(e) {
alert('localStorage.set("' + e.key + '", "' + e.value + '") was called');
};
document.addEventListener("itemInserted", localStorageSetHandler, false);
localStorage.setItem('foo', 'bar'); // Pops an alert
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With