How to detect when a user leaves the site?


I was reading this question: Trying to detect browser close event

But it's not comprehensive enough, or at least I'm not sure it is, I need to detect when the user leaves the website, this could be:

  • internet died
  • PC shuts down (power outage for example)
  • user close the browser
  • user close the browser tab in which the website was running

I'm sure there are more cases.

This probably needs to be managed by the server, and not some javascript event that is not going to be fired in extreme cases.

Any ideas what could be used in this case?.

You could use and listen for when the socket is lost, or you could have your site send a heartbeat to the server and if X milliseconds goes by without a pulse, you can assume the user left for any of the reasons you listed.