DEV Community

Sayuj Sehgal
Sayuj Sehgal

Posted on

How to detect a change in HTML5 Local Storage in the same window?

I want to detect if a local storage variable value is changed or not, But I have noticed that if I added an event listener on 'storage' event, I can detect the change only if I open the same link in ** another window** and then change the local storage value from that window, then it will show me the change in the first window. But I don't want this behavior I just wanted to observe the change in the same window. Is there any way to do it?

Top comments (4)

Collapse
 
amruthpillai profile image
Amruth Pillai

Local Storage is dependent on the domain, so data is shared across tabs. What you are looking for is Session Storage. It is tab-specific and is cleared when the session ends (you can migrate it to local storage later in the UX flow if you want persistence)

Collapse
 
sayuj profile image
Sayuj Sehgal • Edited

Ok, so if I have a Session Storage variable 'firstname' whose value is 'sayuj' (currently) and suppose if i want to fire a function when the value of 'firstname' variable changes

Example:

window.addEventListener('storage',function()=>{
alert('session storage variable value changed');
});

Will this code work?

Collapse
 
amruthpillai profile image
Amruth Pillai

Yes, you would do that. And inside the callback, you can check which variable has changed by performing a diff.

Although, this pattern is not really stable. I'd suggest if you're working on something serious and you have a UI framework like Angular or React, then use the underlying APIs to help you perform this action. For example, in React, you can use reducers to make any change to the app state, the app state can be stored in the sessionStorage as well. I've used a similar data flow architecture in my recent open-source app, but with localStorage instead of session.

Thread Thread
 
sayuj profile image
Sayuj Sehgal

Yeah, I can do this thing with the help of Reducers, Thanks!😊