我想知道是否有一种方法可以使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>
发布于 2021-05-10 02:59:49
一个简单的解决方案是设置一个标志,并在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();
}https://stackoverflow.com/questions/67461348
复制相似问题