I was looking for a consistent solution to this problem some time ago, and my solution was to handle the situation by not trusting the browser or the user.
You cannot know for sure whether the user leaves your page and when, and even if you use "onunload", you will not be able to receive this event before the browser closes or leaves your page. And browser crashes will not give you any signal, so assuming that you know that the user is still viewing your page and can take any further action is a drawback.
The best thing you can do to log out is to set the session timeout, and if you need additional control, you can try adding AJAX calls to critical pages with “I'm alive” signals, and then display users who no longer answer (This will require an AJAX / JS-enabled browser and may exclude potential users).