Logging Out a User On Browser Close

David Pong:
Is there something I can add to kill the session if the user just closes the browser window? Right now if they log in and they close the browser window, opening a new window to same url will not not force them to re validate their login


Delfs:
You can’t consistently detect a terminated browser but you can code other business logic in if you want.
What is the ‘ideal’ desired behavior?


David Pong:
if they close the browser window, it would be like clicking logout button


Delfs:
ok, something like this ( untested ) will prob work

// in onAppLoad or DOM script tag function
window.onbeforeunload = function () {
   localStorage.removeItem('feathers-jwt');
   return ''
};

Delfs:
Yeah that should work! ( if you have other windows open ( multiple tabs) they all must be closed.


This code worked a little better for me. It logs the user out if the tab or window is closed. If the app is open in multiple tabs it logs the user out when the last tab with the app is closed. It does not prompt the user that unsaved changes will be lost:

<script>
    // Logs user out when browser is shut or tab is closed
    function logoutOnClose() {
        localStorage.removeItem('feathers-jwt');
    }

    window.addEventListener('unload', logoutOnClose);
</script>