【问题标题】:How to cancel browser close/refresh confirm modal when refreshing page manually?手动刷新页面时如何取消浏览器关闭/刷新确认模式?
【发布时间】:2018-11-13 19:33:35
【问题描述】:

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

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

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

我试过了:

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

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

【问题讨论】:

  • window.onbeforeunload = null;?

标签: javascript


【解决方案1】:

您可以简单地引入一个全局布尔变量 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;
}

【讨论】:

    猜你喜欢
    • 2022-06-17
    • 2016-09-14
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 2014-01-16
    • 2021-12-17
    相关资源
    最近更新 更多