faqts : Computers : Programming : Languages : JavaScript : Cookie

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

6 of 15 people (40%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

how do you record how long a visitor has been viewing a webpage?

Mar 2nd, 2004 03:19
Neil McGuigan, qsdqsd Gapeau, wicked bob,


It depends on where you want to record it.

Here is an example script that warns the user if they have been on the 
page for too short a time (browsers that support window.onbeforeunload 
event only):

<script type="text/javascript" language="javascript" defer>
<!--

var MinimumViewingTime = 2; //seconds

var startTime;

window.onload = function()
{
  startTime = (new Date()).getTime();
}

window.onbeforeunload = function()
{
  var endTime = (new Date()).getTime();

  if((endTime-startTime) < (MinimumViewingTime * 1000))
  {
    return "You have been on this page less than " + MinimumViewingTime 
+ " seconds.";
  }
}

//-->
</script>

Otherwise, you could post (endTime-startTime) to a server, or save in a 
cookie.