Question

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.

Was it helpful?

Solution

something like that?

var time,timeSite;
window.onload=function(){
 time=new Date();
}


window.onbeforeunload=function(){
 timeSite=new Date()-time;
 window.localStorage['timeSite']=timeSite;
 //store it with whatever serverside language.
}

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.

var x=new XMLHttpRequest;x.open('get','railsurl?time='+timeSite);x.send();

and as @Yiğitcan Uçum mentioned..

why not just use a serverside session to start and end the time spend on a site?

OTHER TIPS

Try this:

var time,timeSite;

  window.onload = function(){
  time = new Date();
 }


   $(window).unload(function () {
     timeSite = new Date() - time;
     $.ajax({
     type: 'GET',
     async: false,
     data: {timespent: timeSite},
     url: '/url/to/rails.com'
   });
 });

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top