我有这个代码:
(function() {
window.onbeforeunload = function () {
alert("hi")
console.log("unloading");
};
})();
我也有这个代码:
window.addEventListener("beforeunload", function() {
alert("hi")
console.log("unloading")
});
它们似乎都不起作用。我想做的就是在用户尝试离开页面时进行记录,但这并没有发生(最新的 Chrome、最新的 Firefox、Edge...),任何人都可以解释为什么它不起作用吗?
最佳答案
Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details. Note also that various mobile browsers ignore the result of the event (that is, they do not ask the user for confirmation). Firefox has a hidden preference in about:config to do the same. In essence this means the user always confirms that the document may be unloaded.
此外,在离开之前使用return
语句提示用户
window.addEventListener("beforeunload", function() {
return "hi";
});
关于javascript - onbeforeunload 根本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37613401/