You could use beforeunload
to call your event before the window closes, even though it may not be compatible with some browsers.
$(window).on('beforeunload',function(){
//meu evento
});
A workaround would be to send a POST in constant time periods telling the server that the user is still online, such as:
var online = setInterval(function (){
//fazer teu post aqui
}, 60000);
So every 60 seconds the user will be updated with the current time, then to check if he is online or not just check if the last time he was seen already has more than 60 seconds.