title: Detect when a user leaves a website
body: <p>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.</p>
  
  <p>Is there a way to determine when the user leaves a page &amp;/or leaves the website for good?</p>
  
  <p>I have successfully coded (in python) the detecting when the user 1st accesses my site (using a cookie) &amp; how to determine what pages they view. <strong>But I don't know how I could detect when they user leaves the website for good?</strong></p>
  
  <p><em>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?</em></p>