10

Is there a way to detect tab close event to clear the localStorage. I need localStorage to share data across tabs. window.onbeforeunload event works fine but it has 2 issues for me:

  1. It also fires on page refresh which I dont want.
  2. I don't need confirm box on tab close.

Like when window is closed the sessionStorage is cleared. At same time I can clear localStorage but don't know what event to bind to. I checked a few questions already available but none seems to address this issue there are workarounds by using flags for click on links and form submits but not a clean way to do it. Kindly suggest any solution for this.

Peter
  • 9,437
  • 14
  • 79
  • 120
  • 2
    Possible duplicate of [How to capture the browser window close event?](http://stackoverflow.com/questions/1631959/how-to-capture-the-browser-window-close-event) – Mike Cluck Aug 24 '16 at 16:48
  • They're saying you can't really do that. [There are other ways of working around it.](http://stackoverflow.com/questions/18783535/jquery-beforeunload-when-closing-not-leaving-the-page) The point is, this question has been asked multiple times. Look through those questions and find what works for your situation. – Mike Cluck Aug 24 '16 at 16:54
  • Then read the other questions. – Mike Cluck Aug 24 '16 at 17:03
  • That's because you just copied and pasted some other code. That code handles if the user submits a form or clicks on a link, not refreshes the page. You need to actually understand the code you're using. Don't just blindly copy it. – Mike Cluck Aug 24 '16 at 17:40
  • hi mike. the above code was for your reference since you were saying about this being duplicate. I know that refresh is not being handled. Thats why i asked a new question! – Peter Aug 24 '16 at 18:03

6 Answers6

14

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);
Berg_Durden
  • 1,219
  • 3
  • 17
  • 34
  • For those who are want to clear local storage after the whole browser session is close (aka close the whole browser rather than the tab) can set a session cookie to check – Kong Nov 26 '21 at 08:17
3

I was able to find solution to this and thought of sharing. Since the window.onbeforeunload event fires on browser/tab close but on refresh as well(which i did not want) the thing was my localstorage was being processed at time of rfresh as well. Which I did not want. In order to overcome this I implemented 1 more event handler window.onload that fires only on refresh and not on tab/browser close where I would reset the localStorage as if nothing had happened. The code is:

window.onbeforeunload = function (e) {
    window.onunload = function () {
            window.localStorage.isMySessionActive = "false";
    }
    return undefined;
};

window.onload = function () {
            window.localStorage.isMySessionActive = "true";
};

I returned undefined in window.onbeforeunload as i did not want a confirm popup to appear on tab/browser close and refresh.

Peter
  • 9,437
  • 14
  • 79
  • 120
  • 1
    Vishal , tried same , onunload function also calling when the page is refreshed in chrome . It doesn't fix issue – Jayanth Suvarna Mar 31 '18 at 10:16
  • @JayanthSuvarna You seem to have not read the answer. It clearly mentions that this behavior is normal and how to resolve it. – Peter Apr 01 '18 at 17:07
  • 1
    Correct me if am not understood , window.onload that fires only on refresh and not on tab/browser close, My observation is here window.onunload will be called first , then it call 'window.onload' during the page refresh , once i clear the localStorage inside event 'window.onunload' how to retrieve back it in window.onload ? – Jayanth Suvarna Apr 02 '18 at 06:19
  • 6
    You set it back to what? You already cleared the localStorage on `onunload` event, which by the way, also clears `isMySessionActive` variable. There's nothing left to be set `onload`. Your solution can be used for clearing the localStorage only on refresh but not on close, in other words, if your question was the other way around. @JayanthSuvarna is totally right in this one. – Tunçel Mert May 18 '18 at 13:22
  • 1
    This is a completely wrong solution what he provided. it will not work this way. – HD.. Dec 07 '20 at 08:40
  • what if the local storage we wanted to use was an dynamic variable instead of true. which we had set from another component itself. – theFrontEndDev Dec 17 '21 at 10:44
3

Check if time between window.onbeforeunload event and window.onload event if it is less than 3 seconds keep the session live else remove the token.

window.onbeforeunload = function (e) {

window.localStorage.unloadTime = JSON.stringify(new Date());

};

window.onload = function () {

let loadTime = new Date();
let unloadTime = new Date(JSON.parse(window.localStorage.unloadTime));
let refreshTime = loadTime.getTime() - unloadTime.getTime();

if(refreshTime>3000)//3000 milliseconds
{
window.localStorage.removeItem("token");
}

};
Swap
  • 159
  • 1
  • 6
2

Use cookie to solve the issue, cookie value will automatically remove on browser close, In my case I am using API with token, that stored in localStorage, so when browser close or shutdown it not logout the user, so what I done is

after login just set cookie with key 'loginstatus' and value 'loggedin'

document.cookie = "loginstatus=loggedin";
localStorage.setItem("token", token);

In the method checking user islogged by using localStorage value

isUserLoggedIn(){
   let session = localStorage.getItem('token');
   if (session == null) {
      return false;
   }else{
      return session
   }
}   

Modified by removing localStorage token if cookie value doesn't exists

isUserLoggedIn(){
  // remove token if cookie not set
  if(this.getCookie("loginstatus") != 'loggedin'){
      localStorage.removeItem("token");
  }

  let session = localStorage.getItem('token');
  if (session == null) {
     return false;
  }else{
     return session
  }
} 

and it worked !!!

YasirPoongadan
  • 563
  • 4
  • 17
0

I know the question is quite old, but maybe someone still needs it.

This solution is not pretty, but it works quite well:

  @HostListener('window:beforeunload')
  setToSession(): void {
    const token = this.authenticationService.currentTokenValue;
    sessionStorage.setItem('tempToken', JSON.stringify(token));
  }

  @HostListener('window:load')
  clearLocalStorage(): void {
    const session = sessionStorage.getItem('tempToken');
    const user = this.authenticationService.currentTokenValue.user;
    const loginMode = user.loginMode;
    console.log(loginMode);
    if (!loginMode && session == null) {
      console.log('TOKEN REMOVED');
      localStorage.removeItem('token');
      window.location.reload();
    }
  }

A temporary token is stored in the sessionStorage when closing/reloading, which is queried when reloading. Only if the token is there and the loginMode is false, the storage is deleted.

-1

Use SessionStorage instead. It gets cleared off whenever the tab is closed.

Bugs
  • 4,456
  • 9
  • 32
  • 40
user2756335
  • 119
  • 1
  • 2