I want to trigger a function when the user exits the web page by closing the browser tab or pressing the browser's back button. Currently, I'm using the "beforeunload" and "unload" events. But when the user reloads the page the download event also fires. Is there a way to solve this?
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {} else {
window.addEventListener('beforeunload', function() {
window.addEventListener('unload', function() {
if (!isSubmit) {
sendDownloadEmail();
}
});
});
window.addEventListener('unload', function() {
if (!isSubmit) {
sendDownloadEmail();
}
});
}
beforeunloadevent is used to capture tab closes and back button presses.pageshowevent is used to differentiate between reloads and actual page exits.wasReloadedflag prevents the function from firing on reloads. Theevent.preventDefault()and event.returnValueinbeforeunloadis optional for displaying a confirmation dialog.