Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture user response when using window.onbeforeunload

Tags:

javascript

dom

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

like image 999
sarsnake Avatar asked Jan 20 '10 18:01

sarsnake


People also ask

What does Window Onbeforeunload do?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.


2 Answers

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.

like image 66
sarsnake Avatar answered Sep 21 '22 01:09

sarsnake


No, browsers allow you to only specify the text in the alert box, but no way to catch the result.

like image 23
jeffreyveon Avatar answered Sep 18 '22 01:09

jeffreyveon