0

On a page, I have a complex form (many fields, tabs...) and i want to show an alert message to warn the user if he tries to leave the page, wether he posted the form or not (because in a edit form, you have all the mandatory fields set, but you can modify or not the values).

I've seen that the possibility of changing the alert message has been remove as Chrome 51 and wasn't working for other browser anyways, but I would like to show a message before the page change, but i would like to show it BEFORE the actual default Chrome/FF, IE ... popup alert.

i'm in more or less in this situation but the answers there are no longer relevant post Chrome 51.

So, from this question

I did

(function ($) {
  'use strict';

$(window).bind('beforeunload', function(e) {
  e.preventDefault();
  $('<div title="Attention !">Vous souhaitez quitter cette page. Avez-vous enregistré les données du formulaire ? Si non, choisissez "rester sur la page" lors de l\'affichage de l\'alerte.</div>').dialog({
    modal:true,
    close: function(){$(this).dialog('destroy').remove();},
    position: { my: "center top", at: "center", of: window }
  });
  return "Random message to trigger the browser's native alert.";
});

}(jQuery));

see the fiddle

but this displays the jQueryUI alert message AFTER the browser alert, so it is no use really.

How can i display this jquery alert BEFORE the actual browser alert, as of 2017 browser usage ? thank you

Overdose
  • 585
  • 7
  • 30

1 Answers1

1

Another implementation you can try:

<html>
  <head>
    <script type="text/javascript">
      var hook = true;
      window.onbeforeunload = function() {
        if (hook) {
          return "Did you save your stuff?"
        }
      }
      function unhook() {
        hook=false;
      }
    </script>
  </head>
  <body>
    <!-- this will ask for confirmation: -->
    <a href="http://google.com">external link</a>

    <!-- this will go without asking: -->
    <a href="anotherPage.html" onClick="unhook()">internal link, un-hooked</a>
  </body>
</html>
Adrian
  • 379
  • 4
  • 10
  • In Chrome version 63 (circa 2018), this works. But instead of getting the warning "Did you save your stuff?", you get the Chrome default message "Changes you made may not be saved." I am sure there is a work around, but for me, the default message is good enough. – Chuck Jan 06 '18 at 19:13