Clear All Session Variables on Form Close RRS feed

  • Question

  • User1556928295 posted

    Haven't seen clear resolution for my issue. I want to clear the session of all the session variables when the user closes the form. I have;

    <body onunload="HandleClose()">

    in the Master page. And;

    function HandleClose() {

    in my SiteJS.js file.

    It says Session is undefined when I step through it. So, how can I clear the Session of all variables when a user closes the form. On a side note, I would also like to update their login SQL Server table when they do. I have it when they log out, but users would rather close the form then log out.

    Wednesday, June 3, 2015 10:51 AM


  • User281315223 posted

    When your browser closes, it is purely a client-side event that has nothing to do with your server-side code and will trigger no events to indicate that the browser was closed. So even if you were able to call your server-side could through an AJAX call or otherwise, you have no guarantee that your server-side code would be executed.

    When the browser is closed, you aren't really going to be able to capture any server-side code (since actually closing the browser is a client-side operation) however there is a Javascript event that is called prior to a window closing called onbeforeunload which can fire a Javascript function when the browser is about to be closed : 

    <script type='text/javascript'>
        //Maps an event to the window closing event
        window.onbeforeunload = function(e) {
            alert("The Window is closing!");

    However, this event as mentioned is handled purely client-side and so you aren't really going to be able to handle any server-side operations within your code-behind and will have no guarantee that the code is going to be executed.

    Possible Solutions

    There are ways to attempt to work around this (such as attempting to navigate the user to another page to handle the logic or making an AJAX call) but you cannot guarantee that your server-side code will execute and "log off" your user properly in all browsers.

    One consideration that you might want to try would be decreasing the duration for your authentication cookie (if you are using Forms Authentication). This will essentially log your user out if they have not been active within the application past the duration of your timeout, which if set to a small value will likely expire prior to the user returning to the application.

    You might also consider using a real-time technology like SignalR to essentially "track" a user throughout your application using their Connection ID and then if you see that they are idle after a certain duration, handle that accordingly and call the Session.Abandon() method.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 3, 2015 11:00 AM