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?
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.
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).
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With