首页 > 解决方案 > 手动刷新页面时如何取消浏览器关闭/刷新确认模式?

问题描述

当用户使用以下代码单击浏览器的刷新或关闭按钮时,我让浏览器显示确认模式:

window.onbeforeunload = confirmCloseOrRefresh;
function confirmCloseOrRefresh() {
   var confirmMessage = confirm('Are you sure to exit?');
   return confirmMessage;
}

现在,我的页面上有一个自定义刷新按钮,我想手动刷新页面而不显示确认模式。

我试过这个:

onRefreshButtonClick(event) {
   event.preventDefault();
   window.location.reload();
   return true;
}

仍然显示确认模式。有什么方法可以取消/覆盖此功能中的确认模式?

标签: javascript

解决方案


您可以简单地引入您在函数restrictUnload中检查的全局布尔变量:confirmCloseOrRefresh

var restrictUnload = true;

function confirmCloseOrRefresh() {
   if (restrictUnload) {
     var confirmMessage = confirm('Are you sure to exit?');
     return confirmMessage;
   } else {
     return true;
   }
}

在您的onRefreshButtonClick函数中,只需将该变量设置为false

onRefreshButtonClick(event) {
   restrictUnload = false;
   event.preventDefault();
   window.location.reload();
   return true;
}

推荐阅读