但我更想知道他是否离开,并按照他的决定做事
如果你想在他离开时做点什么,你可以在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;
});