Search code examples
javascriptanalytics

How to capture visitor time on page


I would like to keep track of how long visitors spend reading a page. If they tab away, or minimize the window, time should not count towards the time on page until they look at the tab again.

I assume some combination of javascript and server side work will be necessary.

A couple of issues I'm struggling with:

  1. What's the best way to store this information in the database?
  2. How do I, with Javascript, capture the time on page with a reasonable degree of accuracy? Do I store events like "page loaded", "user idle", "user returned", "page unloaded", and then separately process all the events in the DB to come up with a time on page?

Solution

  • I've put some work into a small JavaScript library that times how long a user is on a web page. It has the added benefit of more accurately (not perfectly, though) tracking how long a user is actually interacting with the page. It ignores time that a user switches to different tabs, goes idle, minimizes the browser, etc. The Google Analytics method suggested has the shortcoming (as I understand it) that it only checks when a new request is handled by your domain. It compares the previous request time against the new request time, and calls that the 'time spent on your web page'. It doesn't actually know if someone is viewing your page, has minimized the browser, has switched tabs to 3 different web pages since last loading your page, etc.

    https://github.com/jasonzissman/TimeMe.js

    An example of its usage:

    On loading your page:

    document.onload = function() {
      TimeMe.setIdleDurationInSeconds(30);
      TimeMe.setCurrentPageName("my-home-page");
      TimeMe.initialize();  
    }
    

    Retrieving time spent on the page, and sending it to your server when the user leaves your page:

    window.onbeforeunload = function (event) {
        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);
    };