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.