javascript / html - visit duration on page
Is there a wa开发者_开发问答y 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?
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}
});
});
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...
}
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.
精彩评论