Zer*_*001 0 javascript jquery events onbeforeunload
我想在用户离开页面时做一些事情,我添加了这段代码
window.onbeforunload = function (e){
return "You save some unsaved data, Do you want to leave?";
}
Run Code Online (Sandbox Code Playgroud)
该提示可以通知用户,并且用户可以停留在页面上或离开。但是我想更多地了解他是否离开,并根据他的决定做事。我试过了
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
}
}
Run Code Online (Sandbox Code Playgroud)
但是失败了!它总是消失!
有人可以帮助我做到这一点吗?
小智 5
您故意使用的方法(防止事件冒泡)是不可能的,否则您可以阻止用户离开您的页面。
通过执行清理操作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;
});Run Code Online (Sandbox Code Playgroud)
每次都会调用方法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;
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3853 次 |
| 最近记录: |