I am working in project using angular, i want to logout the user when user click on close button or refresh button. Below is the code
document.addEventListener("DOMContentLoaded",function() {
document.addEventListener('visibilitychange', function logData() {
console.log(document.visibilityState)
if (document.visibilityState == "hidden") {
alert("hello")
navigator.sendBeacon('logout');
}
});
})
The problem is when user switches to some other tab in browser, this code executes and user logged out.
I researched on google and find beforeunlod event, but most of the answers saying its not working on mobile.
For refresh (or closing the tab, or closing the browser) we could listen for window:beforeunload to trigger logout. For a button it would be a simple (click) listener event. The onbeforeunload property of the WindowEventHandlers mixin is the event handler for processing beforeunload events. These events fire when a window is about to unload its resources. At this point, the document is still visible and the event is still cancelable.
@HostListener('window:beforeunload')
unloadHandler(event) {
alert("logging out now...")
navigator.sendBeacon('logout');
}
Docs: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#examples