I was following this here to see if I could enable updates on all open webpages of my site if someone has multiple tabs open.
Basically, I set the listener and check to see if the cart
key was changed
window.addEventListener('storage', function(e) {
if (e.key === "cart") {
console.log(`cart changed: ${e.newValue}`);
}
});
When I change localStorage.cart
from another tab on the same website, the event fires just fine in the first tab:
setInterval(function(){
localStorage.cart = "localStorage 1";
setTimeout(function(){
localStorage.cart = "localStorage 2";
},2000);
},4000);
But when I use sessionStorage
instead of localStorage
it doesn't:
setInterval(function(){
sessionStorage.cart = "sessionStorage 1";
setTimeout(function(){
sessionStorage.cart = "sessionStorage 2";
},2000);
},4000);
Does the storage
event only fire for localStorage
and not sessionStorage
?
Tested on chrome only.
The storage event of the Window interface fires when a storage area ( localStorage ) has been modified in the context of another document.
Web storage objects localStorage and sessionStorage allow to save key/value pairs in the browser. What's interesting about them is that the data survives a page refresh (for sessionStorage ) and even a full browser restart (for localStorage ).
The difference is that with sessionStorage , the data is persisted only until the window or tab is closed. With localStorage , the data is persisted until the user manually clears the browser cache or until your web app clears the data.
Yes, users can always modify the values of their own storage.
The sessionStorage is isolated for each tab, so they can't communicate. Events for sessionStorage are triggered only in between frames on the same tab.
These codepens provide a good example
Storage Writer writes to storage
function writeSession()
{
sessionStorage.setItem("test", Math.random());
}
function writeLocal()
{
localStorage.setItem("test", Math.random());
}
Storage Reader listens for storage event (keep this open in a different tab.)
window.addEventListener('storage', function(e) {
if(e.storageArea===sessionStorage) {
$("#output").append('Session storage change <br>');
}
if(e.storageArea===localStorage) {
$("#output").append('Local storage change <br>');
}
});
You will notice that when you press the "Write local" button, in both the iframe and the opened tab the event is captured, but when you press the "Session write" only the embedded iframe captures the event.
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