是否有取消window.onbeforeunload的回调
问题描述:
我没有这方面的实际用例,但我很好奇,是否有办法做出反应(回调),如果用户在触发window.onbeforeunload时点击停留在此页面上。
I don't have an actual use case for this, but I'm curious, whether there is a way to react (callback), if a user clicks on "stay on this page" when window.onbeforeunload was triggered.
function warning(){
if(true){
console.log('leaving');
return "You are leaving the page";
}
}
window.onbeforeunload = warning;
答
停留在页面上没有回调,但有一个用于离开页面, window.unload
。
There is no callback for staying on the page, but there is one for leaving the page, window.unload
.
尝试在 beforeunload
中设置超时,然后在卸载时清除它。如果你留下,超时将会运行,否则它将被清除。
Try setting a timeout in beforeunload
, then clear it in unload. If you stay, the timeout will run, otherwise it'll be cleared.
var timeout;
function warning() {
timeout = setTimeout(function() {
alert('You stayed');
}, 1000);
return "You are leaving the page";
}
function noTimeout() {
clearTimeout(timeout);
}
window.onbeforeunload = warning;
window.unload = noTimeout;