Q:

Calculate time spent on website not single page

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.

A:

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');
}

