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?
+1
A:
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...
}
Jacob Relkin
2010-06-15 14:53:16
it's not guaranteed that the function will really be called every second, there's often a lag ;)
Tobias P.
2010-06-15 15:01:38
+1
A:
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.
VoteyDisciple
2010-06-15 14:54:40
+2
A:
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}
});
});
Mervyn
2010-06-15 14:55:57