Search code examples
c#asp.net-mvctempdata

Is there a way to detect if browser has been closed in a asp.net web mvc 5.0 project?


I am using tempdata for a variable and current have it set in the home controller and in my first last controller I have it removing that key by doing if(TempData.ContainsKey()) TempData.Remove(). I placed that there assuming the user will go from point A to point D where D is the last controller. But I noticed if I close the application throughout any point of the application that the tempdata that was assigned i.e. tempdata["username"] = username will contain the previous value that was entered from the original start of the program and then will be updated after user enters a value to update the key for tempdata. In a asp.net web mvc 5.0 project is there a way to check to see if a browser has been closed so that way I could remove the logic that is inside of the last controller that removes the key into the logic of checking if browser has been closed?


Solution

  • You can detect the tab/browser being closed from javascript using the beforeunload event. Credited Source

    window.addEventListener('beforeunload', function (e) {
        // User is closing the tab/browser
        // You can cancel this event by using e.preventDefault();
        // and for older browsers by using  e.returnValue = '';
    });
    

    From there you can send a message back to your application using AJAX to handle the temp data removal.

    Below using JQuery

    $.ajax({
        method: "POST",
        url: "AbandonSession",
        data: { someVar: "some val" }
    })
    .done(function( msg ) {
        alert( "Session abandoned: " + msg );
    });