In my rails application, I want to track the total time spent on site by individual user.
I did research on it but can not get perfect solution.
How is it possible.
How to track time spent on Web Site
10.3k views Asked by Ganesh Kunwar At
3
There are 3 answers
0
On
The jquery unload ()
event handler can be used to handle this situation,
Example :
Create a server side script say track.php to save all the collected tracking details into a db.
/* Assuming you are tracking authenticated users the */
In Javascript :
var loggedInAt;
var loggedOutAt;
var userId = getUserId ();
function getUserId () {
return userId; // Define a mathod for getting the user if from a cookie or any local variables.
}
function getTotalTimeSpent() {
return (loggedOutAt - loggedInAt);
}
$(document).ready(function() {
loggedInAt = Date.getTime(); // get the start time when the user logged in
$(window).unload(function() {
loggedOutAt = Date.getTime();
totalTimeSpent = getTotalTimeSpent(loggedOutAt, loggedInAt);
$.ajax({
url: "www.yoursite.com/track.php",
method:post,
data: {'TotalTimeSpent': totalTimeSpent, 'UserId' : userId}
})
});
}
In tracking.php :
get the variables $_REQUEST['TotalTimeSpent'] & $_REQUEST['UserId']
and make an insert query to relay the information into the db.
Thanks.
something like that?
if you want more add
window.onblur
this code works.. also ajax would prolly work...
at extreme solution store it in localstorage(like in the example) and then on next login do the ajax.
this works gives you the exact time in seconds...
if you want approx time and for users who don't have localstorage add a setTimeout every 5 min
and update time passed if ajax & localstorage don't work.
here is a ajax call to test with inside the onbeforeunload function.
change
railsurl
whith whatever you need.and as @Yiğitcan Uçum mentioned..
why not just use a serverside session to start and end the time spend on a site?