How to capture when a user is leaving ASP.Net page unexpectedly
<p>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.</p>

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

<pre><code>&lt;script language="JavaScript" type="text/javascript"&gt;
    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?";
    }
&lt;/script&gt;
</code></pre>

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

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

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

<p>Edit:</p>

<p>So I am nearly there:</p>

<p>var prompt = true;</p>

<pre><code>$('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;
    }
})
</code></pre>

<p>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". </p>

<p>Any ideas?</p>

<p>Thanks,
Michael </p>
