Don't clear local storage when the browser is closed , because of many reasons for example the electric power stopped and user couldn't close the browser correctly …
So as a solution i suggest :
1- Manually :
you add a variable to check if a local storage is valide or is a left over from other sessions by an expired updated_at variable
2- Using session unique identifier :
if you are using php you should be able to identify every session using session id
So if you have :
<script>
var sessionId = "<?php echo session_id(); ?>" ;
if( localStorage.getItem("session_id") === sessionId){// getter
//stayed opened a tab/window in same session
}else{
// browser closed detected
//register new session id
localStorage.setItem("session_id", sessionId);// setter
// here you can remove Old data or add new !
}
</script>
Having a unique id for each browser session solves the problem perfectly
3- Using a cookie :
According to some comments and this answer
. You can use cookies that expires when: broswer closes / session ends witch ... has the downside of being unpredictable ...
document.cookie = "key=value; path=/";// do not specify a expiring date
// in order for this to get destroyed with session
You can see the problems of this solution
here