hehofr
hehofr

Reputation: 21

How to clear session when reopen the closest tab in a browser

I can invalidate session when i close the tab or windows of browser, but when i click to reopen the closest tab it loads me the recent page as it is.

I want to redirect to login page if the reopen is clicked, I clear the cookies onUnbeforeUnload but it doesn't work.

here is my code:

`$(window).on("beforeunload", function(e) {
var aCookies=document.cookie.split('; ');
        for (var i = 0; i < aCookies.length; i++) {
            var cookie = aCookies[i];
            var eqPos = cookie.indexOf("=");
            var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
            document.cookie = name + '=0; expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';


        }  
window.location.href = "/safe-unsecured/logout";`
} 

and on load of the page i clear cookies;

Any help would be appreciated

Upvotes: 0

Views: 678

Answers (1)

Tschallacka
Tschallacka

Reputation: 28742

browsers will not load a new page on closing or browsing away from a page. That logout page will never be requested.

Also, as long as the browser is not restarted, the session will exist in the browser. A session is not invalidated by a tab closing, but by the entire browser closing. The only way to really achieve what you want is having your cookies live for one minute and have a timer running that updates the cookie expiry every 10 seconds so it doesn't expire as long as the page is open, or the tab isn't re-opened within a minute.

This is an example of the update code. You'll need to add logic yourself that checks for the existance of the cookie and everything else you need for validation.

window.myCookieValueThatIReadBefore = 'Hello';
  window.setInterval(function() {
     setCookie('cookie_name', window.myCookieValueThatIReadBefore,1)
  }, 1000*10);
  function setCookie(cname, cvalue, exminutes) {
      var d = new Date();
      d.setTime(d.getTime() + (60*1000));
      var expires = "expires="+ d.toUTCString();
      document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }

Upvotes: 1

Related Questions