1

I have found lots of solutions but none of them really solve my problem. I have to perform certain actions on a page if the user decides to leave without saving his changes (ask him if he really wants to leave without saving, or let him save them, and some bookkeeping ). Most answers mention the onbeforeunload event.

Something like

$(window).on('beforeunload ',function() {
    return 'Are you sure ?';
});

But this is not exactly what I need. First, it doesn't let me do a dialog as the user requested. The ideal for me is using a jQuery.UI modal dialog or something similar, with custom messages and two clear buttons: "Leave the page without saving" and "Save and leave" Also, this only control if I could leave or not the page, but I need to do other operations (for example, there are some pages in which the user is allowed to silently save the info and leave... don't ask me, the Business Analyst decided that) So, it is possible to do something like this pseudocode?

  
$(window).on('some event when I leave the page ',
  function() { 
    destiny = DetectDestinyPage();
    if (destiny in list of PagesToAsk and FormHasNotSavedInfo()){
        answer = modalDialogAskingTheClientIfHeWantToSave()
        if(answer == "yes"){
            ajaxCallToServerToSave()
        }
    }
    GoToDestiny(destiny)
  }
}
Nisanio
  • 4,056
  • 5
  • 34
  • 46
  • Possible duplicate of [How can I override the OnBeforeUnload dialog and replace it with my own?](https://stackoverflow.com/questions/276660/how-can-i-override-the-onbeforeunload-dialog-and-replace-it-with-my-own) – hcoat Oct 29 '18 at 03:05
  • You can refer at this link support: https://stackoverflow.com/questions/38879742/is-it-possible-to-display-a-custom-message-in-the-beforeunload-popup/38880926 – son pham Oct 29 '18 at 03:07

2 Answers2

3

Hope this will help you

jQuery(window).bind('beforeunload',function(){
              var Ans = confirm("Are you sure you leave this page!");
               if(Ans==true){
                  return true;
              }else{
                  return false;
               }
 });
PHP Ninja
  • 1,055
  • 2
  • 9
  • 28
  • The confirm dialog doesn't display for me, it just asks "Do you want to reload this page?" I'm pretty sure modals are disabled while handling an onbeforeunload – Ruan Mendes Nov 01 '18 at 04:05
-1

you should get the user's confirm is true or not; you can do like this:

  
$(window).on('some event when I leave the page ',
  function() { 
    let  r=confirm("Are sure to leave?")  // if user click 'yes', r=true, else r=false
    if(r){
      // your code  
    }
  }
}
bolt
  • 90
  • 3