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?
Advertisement
Answer
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>