Session variables are server-side, and closing tabs is a client-side action, so you need to somehow send a signal to the server to clear these session variables.
The most obvious way for me would be to use the onbeforeunload browser method and ajaxically send something to the server to clear the session.
This is a dangerous territory. Are you sure you do not want to allow the user to open and use several tabs of your site at the same time? Because if I have your site open on two tabs, this method will clear the session when one tab is closed, making the other tab useless (not useless, only the rug may have been pulled out from this page, now this session is missing).
Jon smock
source share