如何检测用户何时离开网站
How to detect when a user leaves the site?
我读到这个问题:试图检测浏览器关闭事件
但它还不够全面,或者至少我不确定,我需要检测用户何时离开网站,这可能是:
- 互联网消亡
- 电脑关机(例如停电)
- 用户关闭浏览器
- 用户关闭运行网站的浏览器选项卡
我相信还有更多的病例。
这可能需要由服务器来管理,而不是在极端情况下不会触发的javascript事件。
有什么想法可以在这种情况下使用吗?。
您可以使用socket.io来监听套接字何时丢失,或者您可以让您的站点向服务器发送心跳信号,如果X毫秒过去而没有脉冲,您可以假设用户因您列出的任何原因离开。
我使用Java Script检测离开事件,并向服务器发送ajax请求,以便存储用户离开页面的信息。第二部分是检测用户在我的页面中的时间,每3秒我还会向我的数据库发送一个ajax请求,以保存用户在页面上的时间。
<script>
window.onbeforeunload = function(){//If user left the page
user_left_page();
};
function user_left_page(){//USER LEFT THE PAGE send data to php to store into my database
var action = "left_page";
$.ajax({
url:"includes/track-page-time.inc.php",
method:"POST",
data:{ action: action},
success: function(data){
},
});
}
//This one below is to store the time the user is spending in your page. I am using both
// in my code, basically I keep storing the data every 3 seconds to know the time
setInterval(function () {
update_user_activity();
}, 3000);//Interval time to send the info to the database
function update_user_activity(){//IS USER IN THE PAGE?
var action = "update_time";
$.ajax({
url:"includes/track-page-time.inc.php",
method:"POST",
data:{ action: action},
success: function(data){
},
});
}
</script>
另一种可以跟踪IP/Session Id并保存在数据库中的简单方法是,您可以每隔5或10分钟使用ajax调用更新数据库中的时间。
如果用户没有进行任何活动,并且时间不会更新,如果数据库中的时间小于time()-$intervals,则可以假设用户已经离开,失去了连接等。
您可以在最后两种情况下使用window.onbeforeunload,即检测到浏览器关闭或选项卡关闭事件。对于前两个事件,即电源故障或连接问题,只有连续ping或类似AlienWebguy所说的心跳机制才能实现。
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
参考站点
相关文章:
- jQuery:如何检测用户何时再次滚动到顶部
- 询问用户何时尝试关闭浏览器选项卡
- 一个html/javascript'小工具'知道用户何时单击了小部件外的任意位置
- 如何检测用户何时在主动滚动
- 跟踪用户何时接收到视频的第一个字节
- 如何检测用户何时在Google Places字段中输入无效位置
- jquery检测用户何时滚动到列表顶部
- 如何检测用户何时在输入字段中按Enter键
- 您如何判断用户何时从默认的 JavaScript 提示符 () 中单击取消
- 检测用户何时滚动到对象
- Javascript 事件,用于了解用户何时更改表单上的某些内容
- 检测用户何时从下拉列表中选择选项
- 检测站点的其他用户何时正在键入
- 用于检测用户何时保存网页的 Javascript
- 如何知道用户何时关闭了 Web 应用程序
- 我如何知道用户何时清除我的应用程序的缓存
- 如何检测用户何时离开网站
- 检测用户何时按下返回按钮
- 任何检测用户何时高亮显示或复制全部/部分URL的方法
- 最终用户何时可以看到网页