Capture user response when using window.onbeforeunload

dom, javascript

Solution

Here is the solution I am using in a situation where I need to do something (such as clear the session) ONLY when the user navigates from the page.

I have 2 global vars

var clearSession = true;
var confirmExit = true;


    window.onbeforeunload = function() { return confirmExit(); }
    window.onunload = function() { return clearSession(); }

function confirmExit() {
    if (needToConfirm == true) {       

        return "exit page?";
    }
}


function clearSession() {

     if (clearSession == true) {
        alert("Killing the session on the server!!!");
        PageMethods.ClearSession();
    }
}

Then of course, on every page submit/button/drop down list etc...you need to make sure that the above global variables are set to false.

Hope this helps someone.

Problem

Is there a way to capture whether the user clicked OK or CANCEL? I need to do something ONLY if the user is leaving the page....

Original source