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.
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?