我想在用户离开页面时做一些事情,我添加了这段代码
window.onbeforunload = function (e){
return "You save some unsaved data, Do you want to leave?";
}
此提示可以通知用户,用户可以留在页面或离开。但我更想知道他是否离开,并根据他的决定做事。我试过了,
window.onbeforunload = function (e){
var event = jQuery.Event(e);
var result = confirm('want to leave?');
if (result == false){
//do sth..
event.preventDefault();
}else{
//do clean up
}
}
但是失败了!!它总是消失!
任何人都可以帮我做这件事吗?
你使用的方法(防止事件冒泡)是故意不可能的,否则你可以阻止用户离开你的页面。
您可以通过清理
onunload
实现类似于您想要的东西,并做您一直想做的事情onbeforeunload
.
但我更想知道他走不走,按他的决定做事
如果你想在他离开时做点什么,你可以在
unload
活动中做。例如,正如@Erik Bakker 提到的,您可以在unload
事件中发送异步事件。
但是如果你想知道用户是否“留下”,换句话说取消了离开过程,也有办法。这有点骇人听闻,但它确实有效。
const doSomethingWhenUserStays = function doSomethingWhenUserStays() {
alert('user stayed!!!');
}
window.addEventListener('beforeunload', function onBeforeUnload(e) {
setTimeout(doSomethingWhenUserStays, 500);
// Dialog text doesn't really work in Chrome.
const dialogText = 'A dialog text when leaving the page';
e.returnValue = dialogText;
return dialogText;
});
方法
doSomethingWhenUserStays
每次都会被调用,但是如果用户离开页面,他将看不到它执行了什么。它可以执行异步的东西,同步的,这并不重要,因为它在 setTimeout
之内,因此它不在 onBeforeUnload
的正常流程之外,不会干扰它。
如果你只想在用户真正停留在页面上时执行它,它会稍微困难一些。您必须设置一个全局标志来检查用户是否达到卸载状态,然后才调用
doSomethingWhenUserStays
中的内容。考虑以下示例。
let hasUserLeft = false;
const doSomethingWhenUserStays = function doSomethingWhenUserStays() {
// Perform the following only if user hasn't left the page
if (!hasUserLeft) {
alert('user stayed!!!');
}
}
window.addEventListener('beforeunload', function onBeforeUnload(e) {
// It won't perform doSomethingWhenUserStays in 500ms right after this is called,
// but instead, it will perform it in 500ms after you click "Stay" or "Leave".
// Therefore, there should be some time for `unload` handler to fire and
// set `hasUserLeft` flag before `doSomethingWhenUserStays` is called.
setTimeout(doSomethingWhenUserStays, 500);
// Dialog text doesn't really work in Chrome.
const dialogText = 'A dialog text when leaving the page';
e.returnValue = dialogText;
return dialogText;
});
window.addEventListener('unload', function onUnload() {
hasUserLeft = true;
});
据我在不同的浏览器论坛(如 MSDN、MozillaDev 等)中了解此方法,此方法没有任何针对 OK/Cancel 的回调。你有这个用于确认对话框但不是这个。
这是一个安全实现,允许用户完全有权决定他们应该看到哪个网站。此外,它还可以避免黑客将用户锁定到他们的网站。