Search code examples
javascriptcookieslocal-storagesession-storage

Destroy localStorage if no active tabs for same url are open


I came across an issue today where I am trying to secure users authenticated token. I use session storage to set expiry of session and a serverside cookie that can't be accessed by javascript to store their authentication token. Issue at the moment is that if user opens up a new tab he will not be logged in as there is no expiry in sessionStorage, however token cookie is still present. I am thinking of moving such expiry from sessionStorage to localStorage so that user is still logged in when they open a new tab, but I would like to remove such localStorage entry if there are no active tabs with my website. Is this possible to check for?


Solution

  • You can set the expiration date to current time + x (when x is a short time, let's say a minute). Then write a setInterval call to extend it while your tabs are alive. Something like:

    var expiration = new Date();
    expiration.setMinutes(expiration.getMinutes() + 1);
    window.localStorage.setItem('MyTokenExpiration', JSON.stringify(expiration));
    
    window.setInterval(function() {
        var now = new Date();
        var tokenExpiration = new Date(JSON.parse(window.localStorage.getItem('MyTokenExpiration')));
        if(tokenExpiration.getSeconds() < now.getSeconds() + 30) {
            tokenExpiration.setMinutes(now.getMinutes() + 1);
            window.localStorage.setItem('MyTokenExpiration', JSON.stringify(tokenExpiration));
        }
    }, 30000);