是否有取消window.onbeforeunload的回调 [英] Is there a callback for cancelling window.onbeforeunload
本文介绍了是否有取消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;
DEMO: http://jsfiddle.net/aPwfz/1/
这篇关于是否有取消window.onbeforeunload的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文