I need to clear the session variables when the tab is closed but I could not find any solutions so far. The closest I have got is by using the \"onbeforeunload\" function is
There is no secure way of handling what you are looking for. onbeforunload event executes every time you leave the page. (I had similar problem like this yesterday for one of my projects). The closest you can get is to control how the users leave the page.
See this link posted by lan in some of the comments. And check the answer by Daniel Melo That is as close you can get with the solution from this problem.
I also found this link but its basically the extraction of the answers given in stackoverflow.
Hope this helps.