检测是否通过无关函数取消了nunload事件



我有一个简单的功能,可以在提出新页面请求时显示旋转器叠加。

$(window).on("beforeunload", function() {
  $('#nav-spinner').show();
});

这可以很好地工作..但是,它用于复杂的WordPress网站上,并且还有其他(第三方)组件也使用此事件有时取消导航(例如,在远离部分填充的情况下进行确认形式)。

是否有任何方法可以确定其他功能是否取消了页面卸载,因此我可以在页面上留在页面上立即删除覆盖层。

我想在取消实际导航时要这样做 - 使用计时器删除覆盖层将导致覆盖层过早隐藏或剩下的时间更长。

测试案例显示问题

因此,以下代码显示了您当前拥有的内容。我正在设置背景红色,因为它是最少的代码。

window.addEventListener("beforeunload", function(event) {
  document.body.classList.add("red");
});
// 3rd party code that is showing the "are you sure"
window.addEventListener("beforeunload", function(event) {
  event.preventDefault();
  event.returnValue = 'I am 3rd party code';
});
.red {
  background-color: red;
}
<form>
  <button>Click Me then click "Cancel"</button>
</form>

解决问题

现在,我们已经有了问题的测试案例。当用户单击取消时,背景不应保持红色。那么我们如何检测呢?好吧,没有事件告诉您用户做了什么。

因此,您唯一能做的就是添加一个计时器以删除用户取消其添加的内容。因此,如果他们单击"取消",则计时器运行并删除。

但是,如果他们不取消它,我们该如何将其保留在那里?我们使用卸载来杀死隐藏它的超时。因此,删除超时,不会发射。

var timer
// update the page as page exits
window.addEventListener("beforeunload", function(event) {
  document.body.classList.add("red");
  // if this timer runs, it means beforeunload was cancelled 
  timer = window.setTimeout( function () {
    document.body.classList.remove("red");
  }, 50);
});
   // remove the timer when the pages finally exits so the class is not removed.
window.addEventListener("unload", function(event) {
  window.clearTimeout(timer)
})

 // 3rd party code that is showing the "are you sure"
window.addEventListener("beforeunload", function(event) {
  event.preventDefault();
  event.returnValue = 'I am 3rd party code';
});
.red {
  background-color: red;
}
<form>
  <button>Click Me then click "Cancel"</button>
</form>

您可能必须使用超时毫秒值。可以通过过渡来减少用于显示的内容的闪光,但希望浏览器不会杀死该卸载。

最新更新