Home > Mobile >  Clear local storage on session clear
Clear local storage on session clear

Time:08-09

I want to clear localStorage on session clear, i.e when the user exits the browser.

I am using window.onbeforeunload for this purpose, as shown below.

window.onbeforeunload = function() {
    localStorage.removeItem('myToken');
    return '';
};

The problem is that this function also removes item also on browser reload.

Is there any way around this, or is it any better way on implementing this?

Edit: This is a react app, is there any hook that prevents from clearing local storage on browser reload?

CodePudding user response:

Use sessionStorage. It has the same methods as localStorage, but it clears when the session is cleared.

  • Related