检测用户是否离开网页的最佳方法是什么?
onunload JavaScript事件并不是每次都有效(HTTP请求所花费的时间比终止浏览器所需的时间长)。
创建一个可能会被当前的浏览器阻止。
检测用户是否离开网页的最佳方法是什么?
onunload JavaScript事件并不是每次都有效(HTTP请求所花费的时间比终止浏览器所需的时间长)。
创建一个可能会被当前的浏览器阻止。
当前回答
我知道这个问题已经被回答了,但如果你只想在实际浏览器关闭时触发一些东西,而不仅仅是在页面加载发生时,你可以使用以下代码:
window.onbeforeunload = function (e) {
if ((window.event.clientY < 0)) {
//window.localStorage.clear();
//alert("Y coords: " + window.event.clientY)
}
};
在我的例子中,我正在清除本地存储并用鼠标y坐标提醒用户,只有当浏览器关闭时,这将在程序内的所有页面加载中被忽略。
其他回答
一种(略显笨拙的)方法是用AJAX调用服务器端来替换和链接,指示用户离开,然后使用相同的javascript块将用户带到他们所请求的外部站点。
当然,如果用户只是关闭浏览器窗口或输入新的URL,这是行不通的。
为了解决这个问题,您可能需要在页面上使用Javascript的setTimeout(),每隔几秒钟进行一次AJAX调用(取决于您想要知道用户是否已经离开的速度)。
尝试onbeforeunload事件:它在页面卸载之前被触发。它还允许你询问用户是否真的想要离开。参见onbeforeunload演示。
或者,您可以在他离开时发送Ajax请求。
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
});
在需要执行一些异步代码的情况下(比如向服务器发送消息,说明用户现在没有关注您的页面),beforeunload事件将不会给异步代码运行时间。在异步的情况下,我发现能见度变化和mouseleave事件是最好的选择。当用户更改选项卡、隐藏浏览器或将courser移出窗口作用域时,这些事件将触发。
文档。addEventListener (mouseleave, e = > { //执行一些异步代码 }) 文档。addEventListener (visibilitychange, e = > { 如果文档。visbilitystate === 'visible') { //报告用户处于焦点中 }其他{ //报告用户不聚焦 } })
多亏了Service Workers,在浏览器支持的情况下,完全在客户端实现类似于Adam的解决方案成为可能。只需绕过心跳请求:
// The delay should be longer than the heartbeat by a significant enough amount that there won't be false positives
const liveTimeoutDelay = 10000
let liveTimeout = null
global.self.addEventListener('fetch', event => {
clearTimeout(liveTimeout)
liveTimeout = setTimeout(() => {
console.log('User left page')
// handle page leave
}, liveTimeoutDelay)
// Forward any events except for hearbeat events
if (event.request.url.endsWith('/heartbeat')) {
event.respondWith(
new global.Response('Still here')
)
}
})