猿问

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

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

如果用户离开网页,什么是最好的检测方法?

这个onunloadJavaScript事件并不是每次都能工作(HTTP请求比终止浏览器所需的时间更长)。

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


弑天下
浏览 649回答 3
3回答

白衣染霜花

试试看onbeforeunload事件:它是在页面卸载之前触发的。它还允许您询问用户是否真的想离开。见演示卸载前演示.或者,您可以发送一个阿贾克斯当他离开的时候。

米脂

Mozilla Developer Network有一个很好的描述和示例卸载前.如果您想在离开页面之前警告用户,如果您的页面是脏的(也就是说,如果用户输入了一些数据):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});

四季花海

为此,我使用:window.onbeforeunload = function (e) {}它是在页面卸载之前触发的。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答