Wednesday, April 3, 2013

Recognizing user exit with Socket IO

In Dobly we needed to keep track of which users are currently active. Since Dobly uses Socket IO, I knew I could leverage the disconnect event, but by itself it took several seconds to fire after the user had left, so it wasn't enough by itself - I needed it to fire exactly when the user had left (move to another page, or close the browser or tab).

Recognizing when the exact moment when a user leaves your application can sometimes be tricky. Usually it requires handling the unload event. Many people recommend using the beforeunload event, but I've found that to be inconsistent as you move across different browsers and operating systems. Luckily, Socket IO was there to help.

var socket = io.connect(, {
'sync disconnect on unload': true });

This configuration will indicate to Socket IO to call your disconnect event on browser unload. With this set you don't need to worry about which event do I need to bind for this browser or that. It takes care of all that for you and works consistently across the different browsers.

Hope this helps!

1 comment: