我想在用户通过关闭浏览器选项卡或按浏览器的后退按钮退出网页时触发一个功能。目前,我正在使用“beforeunload”和“unload”事件。但是当用户重新加载页面时,下载事件也会触发。有办法解决这个问题吗
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();
}
});
}
let wasReloaded = false;
window.addEventListener('beforeunload', function (event) {
if (wasReloaded) {
return; // Skip execution if the page was reloaded
}
// Indicate that the page is about to unload
// (can be used for confirmation dialogs or other actions)
event.preventDefault();
event.returnValue = 'Are you sure you want to leave?';
// Trigger the function on actual page exit (not reload)
window.addEventListener('unload', function () {
if (!isSubmit) {
sendDownloadEmail();
}
});
});
window.addEventListener('pageshow', function (event) {
if (event.persisted) {
wasReloaded = true;
}
});