I have seen some websites that logs out user when press browsers back button and also when refresh the page. How can I do this for my website? Is there a absolute solution?
-
window.onbeforeunload = logout; – user875234 Dec 28 '21 at 22:01
-
This question was answered here: https://stackoverflow.com/questions/49547/how-do-we-control-web-page-caching-across-all-browsers – first last Dec 28 '21 at 22:02
-
This [answer](https://stackoverflow.com/a/36444134/231316) has some useful JS – Chris Haas Dec 28 '21 at 22:12
1 Answers
window.addEventListener("beforeunload", func)
is unreliable on mobile browsers. More information on general concerns is discussed here:
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
Logging a user out depends on how the login state is stored. If the login is handled by a cookie, you can register a callback function (addEventListener
) for the beforeunload
or visibilitychanged
event and delete the user's session cookie inside the handler. If logging out requires interaction with a server (e.g. sending an HTTP request to /api/logout
, or something like that), then you may have trouble. You'll have to use XMLHttpRequest. If you use it in asynchronous mode, it's unlikely the User-Agent will actually send/complete the HTTP request as the browser is leaving the page. One workaround is to instead use XMLHttpRequest in synchronous mode. The browser is more likely to complete such a request when it is initiated in a beforeunload
, but not guaranteed. Make sure to implement an additional approach to session expiration (whether server-side expiration or through cookie expiration) in addition to trying this unload/visibilitychange trickery. There is no 100% reliable way to guarantee that your client-side "user leaving the page" JavaScript routine will run every time, even less reliable if you try to send HTTP request inside said event handler.

- 481
- 3
- 5