In JavaScript, you can't directly add an event listener to localStorage
. However, you can listen for storage events on the window
object. The storage
event is fired when a storage area (localStorage
, sessionStorage
) is changed in the context of another document.
Here's an example:
window.addEventListener('storage', function(e) {
console.log(e.key, e.oldValue, e.newValue, e.url, e.storageArea);
});
In the above code:
e.key
is the key that was changed.e.oldValue
is the old value of the key.e.newValue
is the new value of the key.e.url
is the URL of the document where the change occurred.e.storageArea
is the Storage
object that was changed (localStorage
or sessionStorage
).Please note that this event is not fired for changes made in the same document that the listener is in. This is due to the fact that the storage event is only fired when a storage area change is committed in another document, from the same origin (same domain, protocol, and port).
If you want to listen for changes in the same document, you'll need to manually fire a custom event every time you change localStorage
.
// After changing localStorage
localStorage.setItem('key', 'value');
// Dispatch a custom event
window.dispatchEvent(new Event('localStorageChanged'));
// Listen for the custom event
window.addEventListener('localStorageChanged', function(e) {
console.log('Local storage changed!');
});