Reliably sending an event when the user closes the page is almost impossible. There is an onbeforeunload event that may make an Ajax call, but it may fail, fail for security reasons, or fail at all because the user has disabled JavaScript.
This is usually done through session timeouts: it is checked when the last request was made. If it was more than x minutes ago, the session is treated as expired. Isn't that an option?
source share