Reputation: 8655
I was reading this question: Trying to detect browser close event
But it's not comprehensive enough, or at least I'm not sure it is, I need to detect when the user leaves the website, this could be:
I'm sure there are more cases.
This probably needs to be managed by the server, and not some javascript event that is not going to be fired in extreme cases.
Any ideas what could be used in this case?.
Upvotes: 5
Views: 7403
Reputation: 718
I am using Java Script to detect the event of leaving and sending an ajax request to my server so I can store that the user left the page. The second part is to detect the time the user is in my page, every 3 seconds I also send a ajax request to my database to save the time of the user in the page.
<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>
Upvotes: 4
Reputation: 749
You could use the window.onbeforeunload for the last two cases i.e. detecting the browser close or tab close event. For the first two events that is power failure or connectivity problems, only continuously ping or like AlienWebguy said the heartbeat mechanism can be implemented.
Upvotes: 0
Reputation: 683
Another simple method you can track the IP/Session Id and save in the Database, you may update the time in the db using the ajax call in an interval i.e every 5 or 10 minutes.
if user not taken any activity and the time will not be updated, if time in db is less than the time() - $intervals , then you can assume that the user has left, lost connectivity etc.
Upvotes: 1
Reputation: 6156
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?";
}
Upvotes: -1
Reputation: 77966
You could use socket.io and listen for when the socket is lost, or you could have your site send a heartbeat to the server and if X milliseconds goes by without a pulse, you can assume the user left for any of the reasons you listed.
Upvotes: 8