检测用户何时离开网页的最佳方法?
2022-08-30 01:03:26
检测用户是否离开网页的最佳方法是什么?
JavaScript 事件并非每次都有效(HTTP 请求花费的时间比终止浏览器所需的时间长)。onunload
创建一个可能会被当前浏览器阻止。
检测用户是否离开网页的最佳方法是什么?
JavaScript 事件并非每次都有效(HTTP 请求花费的时间比终止浏览器所需的时间长)。onunload
创建一个可能会被当前浏览器阻止。
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
});