About Confirmation Dialog When Trying to Leave a Form with Unsaved Changes

If you want to prevent unsaved changes in forms, you have a chance to display the browser-native dialog with a default message like:

Leave site?
Changes that you made may not be saved.
[Cancel] [Leave]

Here is the JavaScript you would need with jQuery for a page with the form:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$(function() {
  var showLeaveConfirmation = false;

  $(document).on('change', ':input', function() {
    showLeaveConfirmation = true;
  });

  $(document).on('input', '[contenteditable="true"]', function() {
    showLeaveConfirmation = true;
  });

  $('form').on('submit', function() {
    showLeaveConfirmation = false;
  });

  $(window).on('beforeunload', function(e) {
    if (showLeaveConfirmation) {
      e.preventDefault();
      e.returnValue = "";
      return "";
    }
  });
});

The latest versions of modern browsers don't allow customizing the confirmation message.

Tips and Tricks Programming JavaScript jQuery