Search code examples
javascriptasp.netsessionasp.net-membership

Is there a reliable way to log a user out when the browser is closed?


I am looking for a reliable way to log out a user or abandon their session when the browser is closed. Is there a way to do this with tabbed browsers?? Any suggestions are appreciated. Thanks!


Solution

  • There is no reliable way to do this immediately when the client closes the browser. There's the beforeunload event, but even then, when you fire an ajax request during this event, it's not guaranteed to ever reach the server. Still then, you've a problem with multiple browser tabs.

    Most reliable way is to have a relatively short session timeout in the server side (e.g. 1 minute) and introduce an ajaxbased heartbeat on the client side (e.g. every 30 seconds) to keep the session alive.

    There may be better ways depending on the sole functional requirement for which you thought that this is the solution. For example, if your actual intent is to restrict all logins to 1 per registered user, then you'd better collect all logins and the associated sessions and then compare this on each login and invalidate the earlier session if any present. This way it'll work as well on clients with JS disabled.