检测用户何时离开网页的最佳方法?

2022-08-30 01:03:26

检测用户是否离开网页的最佳方法是什么?

JavaScript 事件并非每次都有效(HTTP 请求花费的时间比终止浏览器所需的时间长)。onunload

创建一个可能会被当前浏览器阻止。


答案 1

请尝试以下事件:在卸载页面之前触发它。它还允许您询问用户是否真的想离开。请参阅之前卸载演示的演示onbeforeunload

或者,您可以在Ajax离开时发送他请求。


答案 2

Mozilla Developer Network 有一个很好的描述和 onbeforeunload 的例子

如果您想在离开页面之前警告用户,如果您的页面是脏的(即如果用户输入了一些数据):

window.addEventListener('beforeunload', function(e) {
  var myPageIsDirty = ...; //you implement this logic...
  if(myPageIsDirty) {
    //following two lines will cause the browser to ask the user if they
    //want to leave. The text of this dialog is controlled by the browser.
    e.preventDefault(); //per the standard
    e.returnValue = ''; //required for Chrome
  }
  //else: user is allowed to leave without a warning dialog
});