I am developing a web application , in that I want to log out the user ,only when he closes all the 'tabs' of my application or user closes the browser .
Does anyone know how to do it ?
A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.
To handle the browser tab close even in React: Use the useEffect hook to add an event listener. Listen for the beforeunload event. The beforeunload event is triggered when the tab is about to be unloaded.
The best way I found to reload the page without losing cookies, and remove cookies on window or tab close was to use ng-keydown to watch the F5 Keypress (KeyCode 116).
When we refresh the page (F5, or icon in browser), it will first trigger ONUNLOAD event. When we close the browser (X on right top icon),It will trigger ONUNLOAD event. Now when ONUNLOAD event is triggered, there is no way to distinguish between refresh the page or close the browser.
Try the answer here: Javascript Communication Between Browser Tabs/Windows. Cookies are the usual way to do this. Combine those with the "onunload" event and you should be able to accomplish what you need.
Would be easier, though to simply set your login cookie as "session" by setting the lifetime to 0. This is shared between tabs in most of the browsers I have used and is cleared when the window closes. Only problem is that Internet Explorer tends not to clear session cookies unless the window is closed, not when all tabs of a website are closed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With