Warn Before Closing APEX Modal Dialogs

As you may already know, APEX 5.1 implements native Warn Before Exit functionality. Basically, if the user makes changes on a page and tries to navigate away before they save their changes, they get a warning. Modal Pages also get this feature, with one caveat; the close “X” on the window does not warn.
As I understand, this is was the intended behavior. However, for some use cases, I disagree. For this reason, and after a client’s request, I came up with this solution.
On the Modal Page attributes, we specify a “beforeClose” function. Like so:

Then, on the calling page (or globally) you want the following code:

Line 2 and 3 are the most important to this whole solution. Modal Dialogs run inside an iframe. As such, the calling page needs to take a peek inside the dialog and see if something was changed.
Line 2 gets a hold of the “apex” namespace for the dialog. Line 3 can then check is anything has changed within it.

Finally, line 10, prevents the close even from happening and maintains the dialog opened if they user opts to stay.

I should mention, I tried to use apex.message.confirm instead of the more rudimentary confirm, however because we’re already inside a modal, calling apex.message.confirm would invariably end up closing the modal I wanted to keep open. Perhaps, there’s a way to accomplish this, if you have any ideas, please share in the comments.

Hi, I’m Jorge Rimblas. Father, husband, photographer, Oraclenerd, Oracle APEX expert, Oracle ACE, coffee lover, car guy, gadget addict, etc…

I’m a Senior APEX Consultant with Insum Solutions, a consulting firm specialized in Oracle databases and the APEX development tool. I have worked with Oracle since 1995 and done eBusiness Suite implementations and customizations. Nowadays I specialize almost exclusively in Oracle APEX.

9 comments on “Warn Before Closing APEX Modal Dialogs
  1. Md. Zahidul Islam says:

    Hey… Nice job.

  2. very nice write-up and tip!

  3. Ben says:

    Another great tip! Thanks

  4. AnnelizeF says:

    Great work, thank you!

    I tried this in 5.1.0 and I now get the message on close X, Cancel button and also when I SAVE the record, although the save happens successfully after I OK the message box.

  5. Waqar Ahmed Siddiqui says:

    Great Work, Thank you!

    • Annelize says:

      Hi Waqar, did you get this to work? I get a message for unsaved changes even when I click the SAVE button, although the SAVE button is set to ‘do not check’

I love comments, write me a line