Search code examples
javascriptjquerydom-eventsonbeforeunload

How to show a modal dialog before beforeunload shows its own?


I do understand that it's not possible to replace the beforeunload dialog with a custom one, and that if we need to set a custom message to the user, we'll have to return a string in our beforeunload handler:

{Custom message here set by returning a string in our beforeunload handler}
Are you sure you want to leave this page?
[Leave this page] [Stay on this page]

So, how about showing a custom modal dialog (maybe jQuery) before the actual beforeunload dialog is shown by the browser?

My current code uses Fancybox:

window.onbeforeunload = function() {
    $.fancybox({ 'type':'iframe', 'href':'/PopupOnExit.php' });
    return "Special offer! Stay on this page for more details.";
};

However, this shows the browser's dialog first, and only after clicking either "Stay" or "Leave" buttons does the browser show my modal dialog.

Is there any way to make my modal dialog show before the the browser's dialog?


Solution

  • The DOM modifications take effect only when your script ends execution. In this case, the native dialog is fired first for obvious security reason.

    Note that due to the many security problem introduced by this unspecified feature (see the MDN doc), it will maybe be removed (the soonest the best in my opinion), the old reason to have it (save the data) being obsolete in the age of ajax.