最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to show a modal dialog before beforeunload shows its own? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Feb 25, 2020 at 18:59 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 27, 2012 at 7:12 ObayObay 3,20517 gold badges57 silver badges80 bronze badges 1
  • I edited the question with the browser dialog which I'm referring to – Obay Commented Jun 27, 2012 at 7:16
Add a ment  | 

2 Answers 2

Reset to default 3

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.

unload and onBeforeUnload are very not cross-browser events. Be careful. It's not work in Opera and sometimes in Chrome.

发布评论

评论列表(0)

  1. 暂无评论