N
N
Nikita2020-07-13 13:01:07
JavaScript
Nikita, 2020-07-13 13:01:07

How to find out the time spent on the site in JS (with paging)?

Hello. I need to show a popup to a user who spent 1 minute on the site. He can be on one page, or flip through several pages, but the counter must count the time from entering the site (session time).
Couldn't find anything on google. Can this be done without PHP?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
WapSter, 2020-07-13
@MrNix21

if (!sessionStorage.getItem('startTime')) {
  sessionStorage.setItem('startTime', Date.now());
}

const enterTime = sessionStorage.getItem('startTime')

const showPopup = () => {
  let currentTime = Date.now()
  let spentTime = (currentTime - enterTime) / 1000
  if (spentTime >= 60) {
    clearInterval(timer)
    alert(`Вы провели на сайте минут: ${Math.floor(spentTime / 60)}, секунд: ${Math.floor(spentTime % 60)}`)
  }
}

const timer = setInterval(showPopup, 10000)

But this version will only work within a single tab. And as Ronald McDonald said, such things are generally contraindicated, personally, even in the news, crookedly written lazy loads and other bullshit that starts to move content, not to mention windows that like to cram both by timer, and by scroll, and by click, wildly infuriates me to the document.

R
Ronald McDonald, 2020-07-13
@Zoominger

I need to show a popup to a user who spent 1 minute on the site.

I hate these bastard pop-ups and these filthy chats that come out and fart some sound into my headphones and still draw for a few seconds, not letting me close. Who cares what it says in the pop-up if everyone closes this crap automatically? Damn it, 2k20 is out there, but the fools still shove this feces onto the pages.
On the subject: use cookies, mark the time at which the user entered and check every 10 seconds if the time has exceeded 60 seconds.
Well, on the pop-up you can write: "Goodbye!" to your visitor.

S
Stalker_RED, 2020-07-13
@Stalker_RED

1. Check localStorage, if empty - write the current time.
2. if it's not empty, but the gap is too big, consider that a "new" session has started, update the time in localStorage
3. and compare it with the current one, find out if it's time to show the popup.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question