Capturing a browser window close to give a "Save Entries?" dialog - in jQuery UI

Capturing a browser window close to give a "Save Entries?" dialog - in jQuery UI

I'm hoping to be able to catch a user who is closing the browser window to put up a jQuery UI modal dialog if it's detected that they've made some form changes without saving them. The page is an incremental interview process in an accordion, with the steps each saved using AJAX methods. But if they close without committing a save I'd like to be able to warn them.

I've read a number of forums that give advice regarding this, but it seems to be a moving target.

I've been trying:

  1. // Set up to detect closing the window
  2. $(window).on('beforeunload', function(){
  3. return windowCloseCheck();
  4. }
  5. );

...which has my windowCloseCheck() look for unsaved fields. I've got the return so that I can control whether the window closes or not (that was my theory) by passing on a true or false from the windowCloseCheck().

What happens, though, is that the default browser "Are you sure you want to leave this page?" box comes up, and you have to respond using the opposite-sense button "Stay on Page", in order to get my modal dialog about saving changes if they were detected. If you use what you really want to do, "Leave Page" then the window closes right away.

I'm testing in Safari Version 10.1 (10603.1.30.0.34).

Is this just something that can't really be done cleanly because browsers don't allow it, for our protection?

Troy