Home > Mobile >  How to clear localStorage on browser close?
How to clear localStorage on browser close?

Time:08-18

I need my localStorage to be cleared when browser is closed.

  1. I need shared space for data between tabs and windows with common origin (protocol, domain, port). For example, group of tabs and windows with https://www.reddit.com opened. So sessionStorage is not an option.
  2. I need localStorage to be cleared when browser is closed. Event beforeunload works only when tab is closed. But when entire browser is closed, this event doesnt fire for every opened tab. So storage is not purged.

So I need some hybrid of localStorage and sessionStorage.

CodePudding user response:

Yo can try this solution of clearing the local storage when opening the browser instead of when closing it. Start by checking if there is a value in session storage and if not clear the local storage and then sets a value for the session storage.This will avoid clearing of local storage in future when carring out page refresh.

const  clearStorage = () =>  {
    let session = sessionStorage.getItem('value');
    if (session == null) {
        localStorage.removeItem('remove');
    }
    sessionStorage.setItem('value', 1);
}
window.addEventListener('load', clearStorage);

CodePudding user response:

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

  • Related