1

I need to prompt a user when they are leaving my ASP.Net page unexpectedly with a message to ask if they are sure they want to leave. A post back or when the save button is clicked should not fire the warning. There are a bunch of articles covering this but I am brand new to this and appear to have got my wires crossed.

The recommended way appears to be to use the window.onbeforeunload event but behaves unexpectedly for me. This is fired when the page loads as opposed to when the page unloads.

<script language="JavaScript" type="text/javascript">
    window.onbeforeunload = confirmExit;
    function confirmExit() {
        return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
    }
</script>

If I use the JQuery implementation it fires when the page unloads but the problem is it fires before the code behind is executed. So I cannot set a variable on the client saying don’t fire the event this time as it is a post back or a Save.

$(window).bind('beforeunload', function () {
            return 'Are you sure you want to leave?';
        }); 

Can anyone point me in the correct direction as I know I am making basic mistakes/miss-understanding?

Edit:

So I am nearly there:

var prompt = true;

$('a').live('click', function () {

    //if click does not require a prompt set to false
    prompt = false;
});

$(window).bind("beforeunload", function () {

    if (prompt) {

        //reset our prompt variable
        prompt = false;

        //prompt
        return true;
    }
})

Except the problem is in the above code I need to be able to differentiate between the clicks but I haven't been able to figure that out yet i.e. I am missing a condition here "//if click does not require a prompt set to false".

Any ideas?

Thanks, Michael

2 Answers2

0

You can try using this:

$(window).unload(function(){
  alert('Message');
});
Andrea Turri
  • 6,480
  • 7
  • 37
  • 63
  • Thanks - yes this will fire an alert but not sure if I can get it to throw the same generic prompt as window.onbeforeunload whic I would like as this is what people are generally used to. – Michael Hollywood May 01 '12 at 12:19
  • if you are using database then write routine to check it. By pushing user stat from frontend. – Sunil Chavan May 01 '12 at 12:22
  • there is also "onunload" that is nearest to onbeforeunload, all that you need to do is testing and choose which one is the right for your goal. – Andrea Turri May 01 '12 at 12:23
0

In case people are interested this is the roundabout solution to my problem. How to tell if a page unload in ASP is a PostBack

Community
  • 1
  • 1