3

当用户离开页面时我想做一些事情,我添加了这段代码

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
   }
} 

但是失败了!!它总是消失!

任何机构都可以帮我这样做吗?

4

3 回答 3

6

您使用的方法(防止事件冒泡)是故意不可能的,否则您可能会阻止用户离开您的页面。

通过进行清理,您可以实现与您想要的类似的事情onunload,并做您一直想做的事情onbeforeunload

于 2011-03-10T11:51:20.730 回答
5

但我更想知道他是否离开,并按照他的决定做事

如果你想在他离开时做点什么,你可以在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;
});

于 2018-01-31T14:44:49.080 回答
3

据我在不同的浏览器论坛(如 MSDN、MozillaDev 等)中了解此方法,此方法没有任何 OK/Cancel 回调。你有这个确认对话框,但不是这个。

这是一种安全实施,允许用户完全有权查看他们应该看到的网站。此外,它还可以防止黑客将用户锁定到他们的网站。

于 2011-03-10T12:51:51.013 回答