The only way you can do something when the page is closed or navigated away from is to attach an event handler to the unload event, as Rocket suggests. However, you shouldn't rely on this event to trigger, as a lot of things may prevent it. The browser may stop it on order to focus it's resources on other tasks, the user may loose it's connection, the browser may be terminated, etc.
The most reliable way to keep track of users and session is to have them send keepAlive messages to the server at a given interval. Then you'll know that the user left sometime between a given timestamp and the interval of the keepAlive message.
On the server, you can then traverse the sessions which has not been kept alive for a while and perform any operation you need.
However, this approach won't be necessary if you only need to create some cool "logging off"-effect.