Stop user from leaving page except when form submit or ajax submit

Stop user from leaving page except when form submit or ajax submit

Hi All, I have to make sure on one screen that user don't leave while work is unfinished. I am doing something along this line on the webscreen script tag

function stopPageLeaving( form, buttonId) {
 $(window).bind('beforeunload', function (event) {
        var ret = confirm('work will not be saved. Do you want to Continue ?');
        if( ret == true ){
        $(buttonId).click();} // delete trails in the database on this button click
            return false;}
    $(form).bind('submit', function () {

In the preparation , I am using runJavaScript action like this
stopPageLeaving( '#form1', "'# + buttonName.Id + '")

I have some buttons on the screen submit, ajax submit and navigate. Now form has its own onsubmit "javascript:return WebForm_OnSubmit();" inline which ,i think , takes precedence.

Now it is not working as expected as it is showing the confirm message even on the submit and ajax submit. How this scenario can be handled ? 
I found out the issue. I was trying to do the impossible. You can't modify the default dialogue for onbeforeunload. I was trying to show confirmation box on beforeunload event which is not possible that was the reason on unexpected behavior. I am now taking a different approach for this issue. 

Here is the link

"When a string is assigned to the 
returnValue property of window.event, a dialog box appears that gives users the option to stay on the current document and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered."


Yes, but you won't be able to do the button click thingy with either solution.
Think the max you can do is to check where the user clicked using the event.Target variable. It will be undefined if the user is trying to close the window for example.

Also be carefull with crossbrowser support, since some implement it differently
Here is some documentation with a crossbrowser example:

João Rosado
Yes,you are correct.  I found this out after several hours on pain. Now I have stopped the confirmation altogether and am handling the cleanup based on some logic which is much cleaner than handling it with button click thingy.