The localDataStorage interface (a handy wrapper for the HTML5 localStorage API) conveniently fires change events on the same page/tab/window in which the storage event occurred. (Disclaimer: I am the author of the interface.)
Once you install localDataStorage, this sample code will let you see those change events (and fire off your own required logic in response):
function nowICanSeeLocalStorageChangeEvents( e ) {
console.log(
"subscriber: " + e.currentTarget.nodeName + "\n" +
"timestamp: " + e.detail.timestamp + " (" + new Date( e.detail.timestamp ) + ")" + "\n" +
"prefix: " + e.detail.prefix + "\n" +
"message: " + e.detail.message + "\n" +
"method: " + e.detail.method + "\n" +
"key: " + e.detail.key + "\n" +
"old value: " + e.detail.oldval + "\n" +
"new value: " + e.detail.newval + "\n" +
"old data type: " + e.detail.oldtype + "\n" +
"new data type: " + e.detail.newtype
);
// localstorage has changed; invoke your custom logic here passing in the key that changed
myCustomFunction( e.detail.key );
};
document.addEventListener(
"localDataStorage"
, nowICanSeeLocalStorageChangeEvents
, false
);
The example nowICanSeeLocalStorageChangeEvents() function just spits out key details, but you could easily use it to take specific actions like you mentioned.
For example, if you add a new key
lds.set( 'e2', 101 );
then you'll get something like
message: create new key
method: set
key: e2
old value: undefined
new value: 101
old data type: undefined
new data type: integer
When you delete a key
lds.remove( 'e2' );
then you'll see something like
message: remove key
method: remove
key: e2
old value: 101
new value: undefined
old data type: integer
new data type: undefined
so you can easily respond to local storage key events.
Additionally, via the Broadcast Channel API, localDataStorage can keep other tabs/windows in sync across the same origin. To monitor events, listen on the default channel with a snippet like this
const myChannel = new BroadcastChannel( 'localDataStorage' );
channel.addEventListener( 'message', (event) => {
console.log( event.data );
});
where the listener will receive a JSON of event data.