我在 Chrome、FireFox 和 Safari 上尝试了代码。 onbeforeunload
仍然没有触发。我也尝试了 onunload
,但没有成功。
这是我正在试验的代码:
<!doctype html>
<html lang="en">
<head>
<title> Output to a Page </title>
<meta charset="utf-8">
<script>
window.onload = init;
window.onclick = clk;
window.onbeforeunload = closing;
function clk() {
window.alert("Ouch !!");
}
function closing() {
console.log("function alrt WORKS !!!!");
window.alert("closing now.....");
}
function init() {
var output = "";
for (var mms = 5; mms > 0; mms--) {
if (mms >= 3) {
output += "Still lots of M&Ms left, so eat more!<br>";
} else {
output += "Getting low on M&Ms, take it easy!<br>";
}
}
output += "All out of M&Ms";
var e = document.getElementById("output");
e.innerHTML = output;
}
</script>
</head>
<body>
<p id="output"></p>
</body>
</html>
最佳答案
Onbeforeunload 是 Web 开发者世界中最大的误解之一:D
1) 它拒绝调用所有阻塞的 native 函数(警告、提示、确认)。从用户的 Angular 来看,这是显而易见的。
2) 它(根据 MDN)应该由“addEventListener”(MDN)注册
3) 仅当用户与站点有任何交互时才会触发。没有任何交互(甚至在任何地方单击一次)都不会触发 onbeforeunload 事件。
4) 这个事件的目的是例如。代表用户 secret 保存留在表单(或其他)中的数据(或记录用户行为等)。它不是为了阻止刷新网站!
因此无法显示个性化信息(因为这将一无所获)。
唯一的感觉是在重新加载之前保存的数据时隐藏提示窗口。
5) 如果您想隐藏提示窗口,只需不为 event.returnValue 字段设置任何值即可。
此示例卸载站点(在控制台文本“UNLOAD:1”上写入)在刷新期间没有窗口提示。
window.addEventListener("beforeunload", function(event) {
console.log("UNLOAD:1");
//event.preventDefault();
//event.returnValue = null; //"Any text"; //true; //false;
//return null; //"Any text"; //true; //false;
});
此示例卸载站点(在控制台文本“UNLOAD:1”上写入)在刷新期间带有窗口提示。
window.addEventListener("beforeunload", function(event) {
console.log("UNLOAD:1");
//event.preventDefault();
event.returnValue = null; //"Any text"; //true; //false;
//return null; //"Any text"; //true; //false;
});
您可以将任何类型的值用于 event.returnValue(如右侧所列)。这只是编码风格问题。
event.preventDefault 和 return 都对此事件没有影响(因此在您的代码中您可以省略那些注释行)。
在 Chrome、Edge、Firefox、Opera 上测试(2019 年 9 月 23 日验证)。希望对您有所帮助。
[编辑:]
要避免因意外滑动/拖动屏幕(例如谷歌地图、图像和任何其他稳定内容)而重新加载移动应用程序,这个 CSS 技巧可能很有用:
body { overscroll-behavior-y: contain !important; }
该应用程序将不会被重新加载。
值得考虑为用户提供另一种可能性(例如某些按钮)以在需要时重新加载。
关于javascript - 为什么 onbeforeunload 事件没有触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24081699/