0

I would like log out user when he/she close the browser, but not tab.

I'm aware with the 'beforeunload' event-listener from JS, but that also being call when close tab.

I have a JS function called logout(). How could I call this when user close browser?

1 Answers1

0

You could compare the timestamp of the close event. The browser need more time to close all tabs and so there are a little delay.

//Unload Events
$(window).on('unload',function(e) {
  e = e || window.event;

  var timestamp = localStorage.getItem('timestamp')
  if(timestamp !=null && timestamp !=undefined){
    var TimeNow = new Date().getTime(), Difference  = TimeNow - timestamp ;

    if(Difference<20){
      //Browser Closed
      console.log('Browser Closed')
      localStorage.removeItem('timestamp');
 
      //Your logout function
      logout();
    }else{
      //Tab Closed
      console.log('Browser Tab Closed');
      localStorage.setItem('timestamp',new Date().getTime());
    }

  }else{
    //Other Event
    localStorage.setItem('timestamp',new Date().getTime());
  }
});

There no other solution for this detection.

David H.
  • 11
  • 1
  • I try it and for me it works on the Google Chrome Browser. You can't make an alert or something in this event – David H. Jul 02 '20 at 19:16