0

I want to calculate total time spent on my website not single page in jQuery.

How can i do that? Please share your views.

I can get time spent on single page via handling jQuery unload event but it reset on new page load.

Romulo
  • 4,896
  • 2
  • 19
  • 28
Ashish
  • 83
  • 1
  • 4
  • 1
    Store the value somewhere and modify it with each page. Local storage, a cookie, server-side, etc. – David Sep 11 '17 at 11:47
  • 1
    Possible duplicate of [How to measure a time spent on a page?](https://stackoverflow.com/questions/4667068/how-to-measure-a-time-spent-on-a-page) – Luka Čelebić Sep 11 '17 at 11:49
  • define a global variable check this : https://stackoverflow.com/questions/18995647/jquery-make-global-variable and then in each document access the variable on the ready state. $(document).ready(function(){ // use your own way of handling the time}); – Yamen Nassif Sep 11 '17 at 11:55
  • 2
    To save re-inventing the wheel, use Google analytics. – Rory McCrossan Sep 11 '17 at 12:02

1 Answers1

0

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');
}
Thomas Arbona
  • 976
  • 5
  • 11