How long do your users stay on a page??

Tue, 25th Dec, '07

So … here’s the real deal into measuring how much time a user spends on each individual page by url, and measured in milliseconds.

[1] As soon as page loads, set the current time in a variable in javascript with the help of the onload event. Let this variable be called tstart.

[2] On the unload event, get the current timestamp, and subtract from this the starting timestamp, the first one. So tTotal = tend – tstart.

[3] Now send this time information alongwith location.href to your server, which will record this in a log file, or database to use later, maybe to serve relevant content by keeping in mind a users viewing and browsing patterns.You get the picture right.

So here are the files. Just store monitorme.html & logtimefile.php somewhere on your server and create a writeable file in the same directory named as timelog.txt. Now get monitorme.html and now refresh your page, navigate away to some other page or just plain close the window to find your timelog.txt file piling up with times you spent on the page.


<title>Duration Logging Demo</title>
<script type=”text/javascript”>
var oRequest;
var tstart = new Date();

// ooooo, ajax. ooooooo …
oRequest = new XMLHttpRequest();
else if(window.ActiveXObject)
oRequest = new ActiveXObject(“Microsoft.XMLHTTP”);

function sendAReq(sendStr)
// a generic function to send away any data to the server
// specifically ‘logtimefile.php’ in this case
{“POST”, “logtimefile.php”, true); //this is where the stuff is going
oRequest.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);

function calcTime()
var tend = new Date();
var totTime = (tend.getTime() – tstart.getTime())/1000;
msg = “[URL:” location.href “] Time Spent: ” totTime ” seconds”;
sendAReq(‘tmsg=’ msg);

<body onbeforeunload=”javascript:calcTime();”>
Hi, navigate away from this page or Refresh this page to find the time you spent seeing
this page in a log file in the server.


function logtimemsg($timemsg)
//write your own handling code here, store it in a file or store it in a DB, whatever
$logfilename = ‘timelog.txt’;
if (is_writable($logfilename))
if (!$handle = fopen($logfilename, ‘a’))
if (fwrite($handle, $timemsg.”\r\n”) === FALSE)


UPDATE: People, I love if anyone of you writes back, even if to tell that this doesn’t work. Thanks to JayVee who pointed that <body onunload=”> sucks compared to <body onbeforeunload=”> for this post. Change accomodated.


12 Responses to “How long do your users stay on a page??”

  1. Nancy Says:

    Nice article

  2. Yellen Says:

    a nice and easy way for tracking.

    Nice post sir. I hope u do remember this junior

  3. krahulg Says:

    very well. nice to see you around.

  4. JayVee Says:

    This seems not to be working on FireFox when using tabs. Closing the page, whether it is the active tab or not, doesn’t post back to the server.
    I have found a solution that works (for me) on FireFox and IE (haven’t tested others): simply replace the onload=”javascript:calcTime();” by onbeforeunload=”javascript:calcTime();”.

    Great blog by the way, full of interesting tricks!

  5. krahulg Says:

    Hi JayVee, I was using onunload and not onload. you can check the listing again, and sorry to point out. Do tell me if you find something unusual still and I will rectify it ASAP.
    And I’m glad that you find these things useful. Lets keep talking.

  6. JayVee Says:

    Oh I’m sorry, my mistake, a typo.
    I did mean that it doesn’t work using “onunload” when the page is opened in a tab in FireFox. When the page is the only page displayed, then “onunload” does the trick.
    However “onbeforeunload” works whether the page is tabbed or not.

    Sorry for the confusion.

  7. Stevo Says:

    Your technique will not work on Safari 3.1 (just like my simpler method that doesn’t use Ajax or PHP, but instead just requests an image into an Image object and appends the timespent info as a query string).

    They seem to have deliberately sandboxed the unload and beforeunload event handlers to prevent them from doing anything that involves a http request.

  8. WhAeVeR Says:

    Great Article!
    Works Great!
    Though I haven’t yet managed to get it to work on firefox v3 when the user closes the tab. (even with jayvee solution:using “onbeforeunload”)

    It closes to fast..Got it to work but i had to add an alert(“Leaving..”)

  9. krahulg Says:

    @WhAeVeR: well thanks. do share if you have any ideas and maybe we can improve this …

  10. krahulg Says:

    @stevo: well that’s a revelation, I have to check this and then, we got a situation.

  11. Stevo Says:

    @krahulg – we do got a situation. I tried comp.lang.javascript but not a single reply.

  12. Stevo Says:

    That Safari 3.1 issue where they restrict the actions of an unload handler has been logged. Add your comments to it (the more comments, the more they’ll be motivated to do something).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: