How to Measure a Time Spent on a Page

How to measure a time spent on a page?

If you use Google Analytics, they provide this statistic, though I am unsure exactly how they get it.

If you want to roll your own, you'll need to have some AJAX request that gets sent to your server for logging.

jQuery has a .unload(...) method you can use like:

$(document).ready(function() {
var start = new Date();

$(window).unload(function() {
var end = new Date();
$.ajax({
url: "log.php",
data: {'timeSpent': end - start},
async: false
})
});
});

See more here: http://api.jquery.com/unload/

The only caveat here is that it uses javascript's beforeunload event, which doesn't always fire with enough time to make an AJAX request like this, so reasonably you will lose alot of data.

Another method would be to periodically poll the server with some type of "STILL HERE" message that can be processed more consistently, but obviously way more costly.

Measure time spent by a user during a website visit

Here's a working example. It will stop counting when the user closes the window/tab.

var timer;
var timerStart;
var timeSpentOnSite = getTimeSpentOnSite();

function getTimeSpentOnSite(){
timeSpentOnSite = parseInt(localStorage.getItem('timeSpentOnSite'));
timeSpentOnSite = isNaN(timeSpentOnSite) ? 0 : timeSpentOnSite;
return timeSpentOnSite;
}

function startCounting(){
timerStart = Date.now();
timer = setInterval(function(){
timeSpentOnSite = getTimeSpentOnSite()+(Date.now()-timerStart);
localStorage.setItem('timeSpentOnSite',timeSpentOnSite);
timerStart = parseInt(Date.now());
// Convert to seconds
console.log(parseInt(timeSpentOnSite/1000));
},1000);
}
startCounting();

Add the code below if you want to stop the timer when the window/tab is inactive:

var stopCountingWhenWindowIsInactive = true; 

if( stopCountingWhenWindowIsInactive ){

if( typeof document.hidden !== "undefined" ){
var hidden = "hidden",
visibilityChange = "visibilitychange",
visibilityState = "visibilityState";
}else if ( typeof document.msHidden !== "undefined" ){
var hidden = "msHidden",
visibilityChange = "msvisibilitychange",
visibilityState = "msVisibilityState";
}
var documentIsHidden = document[hidden];

document.addEventListener(visibilityChange, function() {
if(documentIsHidden != document[hidden]) {
if( document[hidden] ){
// Window is inactive
clearInterval(timer);
}else{
// Window is active
startCounting();
}
documentIsHidden = document[hidden];
}
});
}

JSFiddle

Calculate time spent on website not single page

When user enter on any page, you have to know if he navigate between pages or enter on your website. This can be done by look at the last lastLeave data in the local storage (you have to set it when user leave a page). You can do something like that:

window.onload = function onload() {
const now = new Date();
const lastLeave = localStorage.getItem('lastLeave');
if (!lastLeave || now - lastLeave >= MAXTIME_BETWEEN_PAGE) {
localStorage.setItem('lastEnter', now);
}
}

window.onunload = function onunload() {
localStorage.setItem('lastLeave', new Date());
}

function getTimeSpend() {
return new Date() - localStorage.getItem('lastEnter');
}

How to calculate the time a user spends on a website?

One way could be to make your Javascript note down the time when the page loads and also the time when the page unloads(using window.onbeforeunload) and then send this data to your Django backend. Then your backend can calculate the time spent on the page.

Or you can go with the good old method of making your frontend/client poll your server using ajax calls say every 5 seconds so that you will know that the user has spent atleast as long as you got the requests.

Is it possible to know how long a user has spent on a page?

I am assuming that your user opens a tab, browses some webpage, then goes to another webpage, comes back to the first tab etc. You want to calculate exact time spent by the user. Also note that a user might open a webpage and keep it running but just go away. Come back an hour later and then once again access the page. You would not want to count the time that he is away from computer as time spent on the webpage. For this, following code does a docus check every 5 minutes. Thus, your actual time might be off by 5 minutes granularity but you can adjust the interval to check focus as per your needs. Also note that a user might just stare at a video for more than 5 minutes in which case the following code will not count that. You would have to run intelligent code that checks if there is a flash running or something.

Here is what I do in the content script (using jQuery):

$(window).on('unload', window_unfocused);
$(window).on("focus", window_focused);
$(window).on("blur", window_unfocused);
setInterval(focus_check, 300 * 1000);

var start_focus_time = undefined;
var last_user_interaction = undefined;

function focus_check() {
if (start_focus_time != undefined) {
var curr_time = new Date();
//Lets just put it for 4.5 minutes
if((curr_time.getTime() - last_user_interaction.getTime()) > (270 * 1000)) {
//No interaction in this tab for last 5 minutes. Probably idle.
window_unfocused();
}
}
}

function window_focused(eo) {
last_user_interaction = new Date();
if (start_focus_time == undefined) {
start_focus_time = new Date();
}
}

function window_unfocused(eo) {
if (start_focus_time != undefined) {
var stop_focus_time = new Date();
var total_focus_time = stop_focus_time.getTime() - start_focus_time.getTime();
start_focus_time = undefined;
var message = {};
message.type = "time_spent";
message.domain = document.domain;
message.time_spent = total_focus_time;
chrome.extension.sendMessage("", message);
}
}

Time Spend on an Individual Article Page

This is something that you should calculate on client side (e.g. javascript) and not on the server side, because there is no way to ensure that the client will send another request to your server when he finished reading it (by navigating to another page, closing the browser, etc...)

There is an easy solution: Use some already existing analysis-tool like Google Analytics or Matomo (Open Source). They will provide you with statistics how long a user spend on a specific page.

If you want to implement it yourself here is a starting point:
How to measure a time spent on a page?



Related Topics



Leave a reply



Submit