如何检测用户何时离开网站

How to detect when a user leaves the site?

本文关键字:用户 何时 离开 网站 检测 何检测      更新时间:2023-09-26

我读到这个问题:试图检测浏览器关闭事件

但它还不够全面,或者至少我不确定,我需要检测用户何时离开网站,这可能是:

  • 互联网消亡
  • 电脑关机(例如停电)
  • 用户关闭浏览器
  • 用户关闭运行网站的浏览器选项卡

我相信还有更多的病例。

这可能需要由服务器来管理,而不是在极端情况下不会触发的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?";
  }

参考站点