Reputation: 6016
Is there a good way to tell how long a given user spends on a given page of a web application, with an accuracy of about one minute?
One solution that occurred to me would be to use Javascript to hit a web service every minute, and keep track of the hits in a database. But I was wondering if there was a better way... Would there be a way to accomplish this through Google Analytics? If so, how?
Upvotes: 2
Views: 964
Reputation: 2800
For those interested, I've put some work into a small JavaScript library and service that times how long a user interacts with a web page. It actually does exactly what Chase describes in his/her answer! However, it has the added benefit of more accurately (not perfectly, though) tracking how long a user is actually interacting with the page. It ignore times that a user switches to different tabs, goes idle, minimizes the browser, etc.
Edit: I have updated the example to include the current API usage.
An example of its usage:
Include in your page:
<script src="http://timemejs.com/timeme.min.js"></script>
<script type="text/javascript">
TimeMe.initialize({
currentPageName: "home-page", // page name
idleTimeoutInSeconds: 15 // time before user considered idle
});
</script>
If you want to report the times yourself to your backend:
window.onbeforeunload = function(){
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","ENTER_URL_HERE", false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
xmlhttp.send(timeSpentOnPage);
});
TimeMe.js also supports sending timing data via websockets, so you don't have to try to force a full synchronous http request into the document.onbeforeunload
event.
Upvotes: 1
Reputation: 29549
First, I agree with the comments regarding analytics software and you should definitely look into them for things of this nature.
I don't know how well this would work and I definitely don't believe it's the best way to go, but if you're dead set on doing this client side you could perhaps try something like:
var start = new Date().getTime();
window.onbeforeunload = function(){
var end = new Date().getTime();
alert( parseInt(end - start, 10)/60000 + " minutes" );
};
The idea here is to save the current time once a user visits your page. Once they navigate away, the onbeforeunload event should fire and run the function to calculate the time they've spent on the page. I imagine you could add in an ajax call (or something) a synchronous call to save the total time somewhere.
Note: jsfiddle will block these events, but you can still see the output in the error log by opening up the console. Just hit Run
to fire the event once you have the console open.
EDIT:
Please see @Ian's comments below on using an AJAX request inside of the onbeforeunload
event.
Upvotes: 3