How to measure a time spent on a page?

I would like to measure a time (in seconds in integers or minutes in floats) a user spends on a page. I know there is an unload event which I can trigger when they leave the page. But how to get a time they have already spent there?

Answers:

Answer

I'd say your best bet is to keep track of the timing of requests per session ID at your server. The time the user spent on the last page is the difference between the time of the current request, and the time of the prior request.

This won't catch the very last page the user visits (i.e. when there isn't going to be another request), but I'd still go with this approach, as you'd otherwise have to submit a request at onunload, which would be extremely error prone.

Answer

i think the best way is to store time in onload and unload event handlers in cookies e.g. and then analyze them in server-side scripts

Answer

In addition to Jason's answer, here's a small piece of code that should do the trick if you prefer to not use a library, it considers when the user switch tabs or focus another window.

let startDate = new Date();
let elapsedTime = 0;

const focus = function() {
    startDate = new Date();
};

const blur = function() {
    const endDate = new Date();
    const spentTime = endDate.getTime() - startDate.getTime();
    elapsedTime += spentTime;
};

const beforeunload = function() {
    const endDate = new Date();
    const spentTime = endDate.getTime() - startDate.getTime();
    elapsedTime += spentTime;

    // elapsedTime contains the time spent on page in milliseconds
};

window.addEventListener('focus', focus);
window.addEventListener('blur', blur);
window.addEventListener('beforeunload', beforeunload);
Answer

According to the right answer I think thats is not the best solution. Because according to the jQuery docs:

The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers and contrasted with the similar beforeunload event.

Another thing is that you shouldn't use it after documents load because the result of substraction of time can be fake.

So the better solution is to add it to the onbeforeunload event in the end of the <head> section like this:

<script>
var startTime = (new Date()).getTime();

window.onbeforeunload = function (event) {
    var timeSpent = (new Date()).getTime() - startTime,
        xmlhttp= new XMLHttpRequest();
    xmlhttp.open("POST", "your_url");
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
    xmlhttp.send(timeSpent);
};
</script>

Of course if you want to count the time using Idle detector you can use:

https://github.com/serkanyersen/ifvisible.js/

TimeMe is a wrapper for the package that I paste above.

Answer
<body onLoad="myFunction()">
<script src="jquery.min.js"></script>
<script>
var arr = [];
window.onbeforeunload = function(){
var d = new Date();
var n = d.getTime();
arr.push(n);
var diff= n-arr[0];
var sec = diff/1000;
var r = Math.round(sec);
return "Time spent on page: "+r+" seconds";
};
function myFunction() {
var d = new Date();
var n = d.getTime();
arr.push(n);
}
</script>
Answer

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.

Answer

The accepted answer is good, but (as an alternative) I've put some work into a small JavaScript library that times how long a user is on a web page. It has the added benefit of more accurately (not perfectly, though) tracking how long a user is actually interacting with the page. It ignore times that a user switches to different tabs, goes idle, minimizes the browser, etc. The Google Analytics method suggested in the accepted answer has the shortcoming (as I understand it) that it only checks when a new request is handled by your domain. It compares the previous request time against the new request time, and calls that the 'time spent on your web page'. It doesn't actually know if someone is viewing your page, has minimized the browser, has switched tabs to 3 different web pages since last loading your page, etc.

Edit: I have updated the example to include the current API usage.

Edit 2: Updating domain where project is hosted

https://github.com/jasonzissman/TimeMe.js/

An example of its usage:

Include in your page:

<!-- Download library from https://github.com/jasonzissman/TimeMe.js/ -->
<script src="timeme.js"></script>
<script type="text/javascript">
TimeMe.initialize({
    currentPageName: "home-page", // page name
    idleTimeoutInSeconds: 15 // time before user considered idle
});
</script>

If you want to report the times yourself to your backend:

xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","ENTER_URL_HERE",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
xmlhttp.send(timeSpentOnPage);

TimeMe.js also supports sending timing data via websockets, so you don't have to try to force a full http request into the document.onbeforeunload event.

Answer

???????????? ????????????????????????????????????????????.????????????()

Running inline code to get the time that the user got to the page blocks the loading of the page. Instead, use performance.now() which shows how many milliseconds have elapsed since the user first navigated to the page. Date.now, however, measures clock-time which can differ from navigation-time by a second or more due to factors such as Time resynchonization and leap seconds. performance.now() is supported in IE10+ and all evergreen browsers (evergreen=made for fun, not for profit). The earliest version of internet explorer still around today is Internet Explorer 11 (the last version) since Microsoft discontinued Windows XP in 2014.

(function(){"use strict";

var secondsSpentElement = document.getElementById("seconds-spent");
var millisecondsSpentElement = document.getElementById("milliseconds-spent");

requestAnimationFrame(function updateTimeSpent(){
    var timeNow = performance.now();
    
    secondsSpentElement.value = round(timeNow/1000);
    millisecondsSpentElement.value = round(timeNow);
    
    requestAnimationFrame(updateTimeSpent);
});
var performance = window.performance, round = Math.round;
})();
Seconds spent on page:&nbsp; <input id="seconds-spent" size="6" readonly="" /><br />
Milliseconds spent here: <input id="milliseconds-spent" size="6" readonly="" />

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.