Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine Time On Site in Javascript?

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?

like image 383
Max Schmeling Avatar asked Feb 26 '09 18:02

Max Schmeling


2 Answers

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.

like image 134
Eric Petroelje Avatar answered Oct 26 '22 07:10

Eric Petroelje


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.

like image 43
Beau Avatar answered Oct 26 '22 05:10

Beau