Clear localStorage on tab/browser close but not on refresh

I know that that is an old question, but I was just looking for a solution for this, but I couldn’t find anything that works properly. Then I came up with a solution which is working fine for me.

What I did was to change the perspective, instead of clearing the local storage when the browser is closed I decided to clear it when it is opened. Users won’t see the difference.

I just set a function that check the sessionStorage when the page is loaded, if it is empty the function gets the localStorage cleared; After that it sets a register to sessionStorage to ensure that the localStorage won’t be emptied again just for having the page reloaded.

function clearStorage() {

    let session = sessionStorage.getItem('register');

    if (session == null) {
    
        localStorage.removeItem('remove');

    }
    sessionStorage.setItem('register', 1);
}
window.addEventListener('load', clearStorage);

Leave a Comment