onbeforeunload confirmation screen customization

限于喜欢 提交于 2019-11-27 09:43:53
window.onbeforeunload = function (e) {
  var message = "Your confirmation message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

  // For Safari
  return message;
};

Please note: Most browsers put this message after some other text. You do not have complete control of the content of the confirmation dialog.

No, you can't avoid the standard one from the browser. All you can do is inject some custom text into it; if you use the following event handler (registered the prototype lib way):

Event.observe(window, "beforeunload", function(event) {
    if (showMyBeforeUnloadConfirmation)
        event.returnValue = "foo bar baz";
});

(and showMyBeforeUnloadConfirmation is true) you'll get the browser's standard confirmation with the following text:

Are you sure you want to navigate away from this page?

foo bar baz

Press OK to continue, or Cancel to stay on the current page.

[ OK ] [ Cancel ]

Imran Rizvi

I faced the same problem, I was able to get its own dialog box with my message, but the problems I faced were:

  1. It was giving message on all navigations and I wanted it only for close click.
  2. With my own confirmation message if user selects "Cancel", it still shows the browser's default dialog box.

Following is the solutions code I found, which I wrote on my Master page.

function closeMe(evt) {
    if (typeof evt == 'undefined') {
        evt = window.event;
    }
    if (evt && evt.clientX >= (window.event.screenX - 150) && evt.clientY >= -150 && evt.clientY <= 0) {
        return "Do you want to log out of your current session?";
    }
}

window.onbeforeunload = closeMe;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!