tags:

views:

228

answers:

3

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

+2  A: 

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

jeffreyveon
oh great, this function is a lot of use then (sarcasm). moving on to onunload
gnomixa
Either this is completely wrong or I am going insane. I know it's possible to show a confirm dialog on unload; this very site does so if you hit Back while editing a post.
iandisme
@gnomixa are you kidding? I'm *glad* browsers don't give this power to the scripting.
Peter Bailey
@iandisme: Yes, you can show a confirm dialog, but this is automatically done by the browser (you can only define what text shows up in it). And there is no way to catch the result.
jeffreyveon
Ahhh I see. I misunderstood the question. +1 and I'm going to grab another cup of coffee.
iandisme
@iandisme You see a dialog, yes, but it's not a `confirm` as in `window.confirm()` dialog. It's a separate dialog scheme that does not have a readable return value.
Peter Bailey
A: 

Use the confirm dialog.

See also: http://bytes.com/topic/javascript/insights/825556-using-onbeforeunload-javascript-event

Sean Vieira
confirm will not close the window. See my solution here.
gnomixa
+1  A: 

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.

gnomixa