onbeforeunload 事件异常?

问题描述

我想知道是否有办法在任何其他情况下触发 onbeforeunload 事件警报,除了特定功能引起的页面重新加载。

之前回答的大多数问题最多只有 3 岁。

window.addEventListener('beforeunload',function (e) {

e.preventDefault();

e.returnValue = '';

});

document.getElementById("reload").addEventListener("click",myFunction);

function myFunction() {

location.reload();

}  // I WANT TO EXCLUDE THIS FUNCTION FROM ONBEFOREUNLOAD EVENT ALERT
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
<button id="reload">RELOAD FROM HERE SHOULD NOT TRIGGER ONBEFOREUNLOAD ALERT</button>
</body>
</html>

解决方法

一个简单的解决方案是设置一个标志,并在 beforeunload 侦听器中检查该标志:

let beforeUnloadAlert = true;
window.addEventListener('beforeunload',function (e) {
  if (!beforeUnloadAlert) return;

  // etc
  e.preventDefault();
  e.returnValue = '';
});
function myFunction() {
  beforeUnloadAlert = false;
  location.reload();
}

另一种方法是在调用 .reload 之前移除侦听器,方法是将侦听器放入命名函数中:

window.addEventListener('beforeunload',unloadHandler);
function myFunction() {
  window.removeEventListener('beforeunload',unloadHandler);
  location.reload();
}