I've searched for a consistent solution to this problem some time ago, and my decision was to handle the situation without believing the browser or the user.
You can't for sure know if a user is leaving your page and when, and even if you use 'onunload', you may not get the event before the browser closes or leaves your page. And browser crashes won't give you any kind of signal, so believing you know the user is still viewing you page and may take any further action is flawed.
The best you can do about logging out an user is put a fitting session timeout, and if you need further control, you may try adding AJAX calls on critical pages with 'I'm alive' signals, and then logging out users that are not responding anymore (that would require AJAX/JS enabled browser and may exclude potential users).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…