1

I have this jquery code that shows a dialog pop up when user is trying to leave the page when there are unssaved changes. The dialog shows but still proceeds to leave the page. What I'm trying to do is the user will click the button inside the dialog pop up whether he wants to leave or cancel.

Dialog Pop Up

<div id="dialog" title="Basic dialog">
                        <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
                        <input type="submit" value="Leave" />
                        <button onclick="window.history.back();">Cancel</button>
</div>

JQuery

 $(document).ready(function () {
            //place above code here
            var somethingChanged = false;
            var btnClicked = true;
            $('.form-group').change(function () {
                somethingChanged = true;
            });
            $('#save').click(function () {
                btnClicked = false;
            });
            $(window).bind('beforeunload', function (e) {
                if (somethingChanged == true && btnClicked == true) {
                    $(function () {
                        $("#dialog").dialog();
                    });
                } else {
                    e = null;
                }
            });
            
        });
JOJO
  • 81
  • 1
  • 2
  • 9

1 Answers1

1

It is not possible to prevent page closing with the help of some custom dialog. This is done due to security reasons. What you can do it to show browser default prompt dialog by using this code (taken from 2):

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});

Move information:

  1. stackoverflow

  2. MDN

omalyutin
  • 445
  • 7
  • 24