Skip to content
Advertisement

Detect user exit site

I have an urge to detect when a user leaves my site in order to record accurately the session length of the user in question. I have thought of a couple possible solutions for this:

I first thought I could use onbeforeunload and send a simple ajax to record the last activity but what practice has shown me is that onbeforeunload is unreliable for now and it’s a bad idea to use it since it’s not cross browser.

Then I thought I could use cookies to record the user’s session length, respectively increase the cookie value every time a user has shown activity. The problem here is that I cannot detect which would be the user’s last activity and the only possible way I can safely insert the session length and know it’s accurate is when the user hasn’t logged in for quite some time and the cookie’s value would be the last session length. This wouldn’t be suitable for me because many users may just open the site once and never visit it again ( for example ), then none of those users would be recorded.

Does anyone have a solution for this issue? I seem to have searched but none of the answers I found were satisfying.

Thank you in advance!

Advertisement

Answer

This question seems to be getting some attention, so I thought I’d update the answer as it has been nearly 10 years.

WebSockets have come a long way since 2013, and a socket can be used to determine the (almost) exact moment the user leaves a site.

It might not be such a good idea on a website with a lot of traffic as it might require sophisticated management and is more than likely to not be available on shared hosting, so make sure you are familiar with the technology before using it.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement