I am trying to capture browser events like tab-close and refresh in my angular 6 Application. It's working fine in debug mode but its not working if I close debug mode and run the application. below is the piece of code
registerDOMEvents() {
window.addEventListener('unload', () => {
if (this.validNavigation === 0) {
this.endSession();
}
});
document.addEventListener('keydown', (e) => {
const key = e.which || e.keyCode;
if (key === 116) {
this.validNavigation = 1;
}
});
}
endSession() {
this.logout();
localStorage.clear();
}
ngOnInit() {
this.registerDOMEvents();
}
What might me the problem for this issue?
You need to use beforeunload
instead of unload
. beforeunload
is more reliable and triggers when the document and its resources are about to be unloaded whereas unload
fires when page is already unloading.
Your endSession()
must be synchronous, since browser will not wait when any callbacks will be called. As I know angular http service doesn't provide synchronous http calls, but you can do it by yourself with XMLHttpRequest
:
window.addEventListener("beforeunload", function (event) {
var client = new XMLHttpRequest();
client.open("POST", "http://url/to/endsession", false); // third parameter indicates sync xhr
client.setRequestHeader("Content-Type", "application/json");
client.send('{userId: "42"}');
console.log('done!!!'); // outputs when a response is received
});
Also take a look this article. Probably you can use navigator.sendBeacon
if a browser of your clients supports that feature.