Clearing SESSION variables when a tab is closed

16,233

Solution 1

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.

Solution 2

Unfortunately, there is no way to prevent page refresh (caused by form submit or any other navigation) from calling "onbeforeunload".

Share:
16,233
Bhuns
Author by

Bhuns

Updated on June 23, 2022

Comments

  • Bhuns
    Bhuns almost 2 years

    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 javascript.

    <body onbeforeunload='destroySession()'>
        <!--Codes for the site includeing php scripts-->
    </body>
    <script type='text/javascript'>
        function destroySession(){
            $.ajax({
               url: "destroySession.php"
            });
         }
    <script>
    

    The problem is the function is called every time a new link is clicked, refreshed or even if a form is submitted. Is there a better way to destroy session variables on closing a tab or am I doing something wrong? Please help.

  • Kevin B
    Kevin B over 10 years
    however you can somewhat detect whether or not it was due to a form post or anchor click.