Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when a user leaves a website

Tags:

I am trying to create my own website access library (for fun) like Google Analytics where I can detect when a user accesses my website, what pages they view etc.

Is there a way to determine when the user leaves a page &/or leaves the website for good?

I have successfully coded (in python) the detecting when the user 1st accesses my site (using a cookie) & how to determine what pages they view. But I don't know how I could detect when they user leaves the website for good?

Is there a way in javascript (maybe I can detect when the page/url is changing?). I know in HTTP there is a referrer header that tells me where the user came from, maybe when the user moves to another website (outside of mine), I can be notified of this (because I will be the referrer in that HTTP request)? Am I correct?

like image 586
Mack Avatar asked Apr 07 '11 03:04

Mack


People also ask

How can I find out if someone is leaving a website?

Try the onbeforeunload event: It is fired just before the page is unloaded. It also allows you to ask back if the user really wants to leave. See the demo onbeforeunload Demo. Alternatively, you can send out an Ajax request when he leaves.

Which event triggers when the user leaves the page?

The beforeunload event on window triggers when the user wants to leave the page. If we cancel the event, browser asks whether the user really wants to leave (e.g we have unsaved changes).


2 Answers

As long the user plays by the rules you expect the onbeforeunload will work. That means, closing a tab, or closing the window, or navigating to another site.
However, you have no way to detect this reliably with javascript, onbeforeunload doens't fire in many cases, such as shutting down the browser (ctrl+q), browser crash, history (back) and opera and some versions of chrome have limited support to onbeforeunload.

If you want to detect it with high precision, you must send Ajax requests periodically that shows the user is "still alive". register those requests in a database or file and analyze it by the time sequence.
So, if you "ping" the database every 20 seconds you can know from pretty simple queries that the browser hasn't "pinged" after a short while, and determine the user is no longer in the site.

like image 45
user1134422 Avatar answered Nov 27 '22 20:11

user1134422


Using jquery you can trigger this:

$(window).bind('beforeunload', function() {     // ajax call perhaps     // triggering a write to db or filesystem... }); 

Pure javascript way:

<html> <head> <script> function closeIt() {   return "Any string value here forces a dialog box to \n" +           "appear before closing the window."; } window.onbeforeunload = closeIt; </script> </head> <body>   <a href="http://www.somewhere.com">Click here to navigate to        www.somewhere.com</a> </body> </html> 
like image 173
hoopyfrood Avatar answered Nov 27 '22 20:11

hoopyfrood