How to determine Time On Site in Javascript?

2019-04-06 15:55发布

Google Analytics tracks 'Time On Site'. How would you do that effectively? Does it actually track when the user closes the browser or navigates away?

Thoughts?

5条回答
贼婆χ
2楼-- · 2019-04-06 16:13

There is a javascript event called onBeforeUnload which executes when a user leaves a page. This could include closing the windows/tab or navigating to a different page(even if it's on the same site). By getting the time immediately after the page loads and using JavaScript to send a synchronous request onBeforeUnload with the difference in time between loading and leaving, you can effectively track the time spent on a page. I would assume this is what Google does.

If you want working code examples and a little more info, check this out.

查看更多
祖国的老花朵
3楼-- · 2019-04-06 16:17

Just set a function like this:

function track()
{
   setTimeout(track ,1000);
   now = new Date;
   now_string = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
   (... whatever you want to do with this data)
}

In javascript you get like that a string saying HH:MM:SS, or H:M:S in case the hour/minute/second number as less than 2 characters

So just make a bit of math arround it

Just put this running somewhere in your window, and associating it with the session (guaranteing this is in all pages) you get exactly how much time some user was in your page.

Edit: had to remove a function i had there that was mine and it isn't from javascript sry :p

查看更多
来,给爷笑一个
4楼-- · 2019-04-06 16:30

I don't think that it tracks when you close the browser or navigates away, and even if it does, that doesn't work in 100% of the cases.

My guess is that they estimate the stay at the exit page, perhaps based on the previous pages or an average for that page for all visitors. If you get three page hits in a few minutes, you have an exact viewing time for the first two pages, but you never know how long the third page is viewed. Perhaps you close the page right away, or leave it open and read it later.

It's statistics, so in the long run it's usually rather accurate, but it's never really the truth. ;)

查看更多
Deceive 欺骗
5楼-- · 2019-04-06 16:32

I suspect they probably run a timer that repeats and executes some kind of callback on each loop using a cookie to identify the user and session

查看更多
Root(大扎)
6楼-- · 2019-04-06 16:35

I can't be 100% certain of course, but I would guess they use javascript and the onload and onunload events and/or setTimer to communicate with a web service via AJAX. This way they could figure out when users go to or leave a page on your site. Once the browser stops "pinging" the web service, it's assumed that they left your site.

I'm sure there's some margin of error involved no matter how you do it, but you could get a pretty decent estimate that way.

查看更多
登录 后发表回答