Richard Knop Richard Knop - 3 months ago 7x
jQuery Question

How to measure a time spent on a page?

I would like to measure a time (in seconds in integers or minutes in floats) a user spends on a page. I know there is an unload event which I can trigger when they leave the page. But how to get a time they have already spent there?


If you use Google Analytics, they provide this statistic, though I am unsure exactly how they get it.

If you want to roll your own, you'll need to have some AJAX request that gets sent to your server for logging.

jQuery has a .unload(...) method you can use like:

var start;

$(document).ready(function() {
  start = Date.getTime();

  $(window).unload(function() {
      end = Date.getTime();
        url: "log.php",
        data: {'timeSpent': end - start}

See more here:

The only caveat here is that it uses javascript's beforeunload event, which doesn't always fire with enough time to make an AJAX request like this, so reasonably you will lose alot of data.

Another method would be to periodically poll the server with some type of "STILL HERE" message that can be processed more consistently, but obviously way more costly.