blank bank
blank bank

Reputation: 375

javascript / html - visit duration on page

Is there a way to use javascript to determine how long someone was looking at my webpage before they closed their browser or hit the back button? Something like send a message to php page every few seconds or so in the background?

Upvotes: 0

Views: 2164

Answers (3)

Jacob Relkin
Jacob Relkin

Reputation: 163228

Start a timer when the page is loaded and when the page is unloaded, stop it.

var timeSpent = 0; //seconds on page
var timer;
window.onload = function() {
  timer = setInterval( function() { timeSpent++; }, 998 );
};

window.onunload = function() {
  timer = clearInterval( timer );
  //.. do something with timeSpent here...
}

Upvotes: 2

Mervyn
Mervyn

Reputation: 1051

There are several ways you could implement this using AJAX techniques.

Using JQuery:

var startTime = new Date();    
$(window).unload(function() {
  var endTime = new Date();
  $.ajax({
    url: "yourpage.php",
    data: {start: startTime, end: endTime}
  });

});

Upvotes: 3

VoteyDisciple
VoteyDisciple

Reputation: 37803

You could also try running an AJAX request in the onUnload event. That would give a more accurate time (with less network traffic, obviously) than periodic polling.

Upvotes: 1

Related Questions