When using window.onbeforeunload (or $(window).on("beforeonload")), is it possible to display a custom message in that popup?

Maybe a small trick that works on major browsers?

通过查看现有答案,我觉得在过go 使用confirmalertevent.returnValue这样的东西是可能的,但现在它们似乎不再有效了.

So, how to display a custom message in the beforeunload popup? Is that even/still possible?

推荐答案

tl;dr - You can't set custom message anymore in most modern browsers

A quick note (since this is an old answer) - these days all major browsers don't support custom message in the beforeunload popup. There is no new way to do this. In case you still do need to support old browsers - you can find the information below.

In order to set a confirmation message before the user is closing the window you can use

jQuery

$(window).bind("beforeunload",function(event) {
    return "You have some unsaved changes";
});

Javascript

window.onbeforeunload = function() {
    return "Leaving this page will reset the wizard";
};

      It's important to notice that you can't put confirm/alert inside beforeunload


还有几点注意:

  1. NOT all browsers support this (more info in the Browser compatibility section on MDN) 2. In Firefox you MUST do some real interaction with the page in order for this message to appear to the user.
    3. Each browser can add his own text to your message.

Here are the results using the browsers I have access to:

Chrome:

Chrome alert on exit

Firefox:

Firefox alert on exit

Safari:

Safar alert on exit

IE:

IE alert on exit

只是为了确保-您需要包含jQuery

有关浏览器支持和删除自定义消息的更多信息:

  1. Chrome removed support for custom message in ver 51
  2. Opera removed支持38版中的自定义消息
  3. Firefox removed support for custom message in ver 44.0 (still looking for source for this information)
  4. Safari removed支持9.1版中的自定义消息

Jquery相关问答推荐

jQuery .append() 创建两个元素而不是一个

Twitter Bootstrap 是否包含 jQuery?

如何在 jQuery 中获取浏览器滚动位置?

获取单选按钮组的值

如何判断是否有任何 JavaScript 事件侦听器/处理程序附加到元素/文档?

非 AJAX jQuery POST 请求

在网络浏览器中,onblur 和 onfocusout 有什么区别?

如何使用Angular 检测浏览器后退按钮单击事件?

为特定请求禁用 ajaxStart() 和 ajaxStop()

jQuery Force 为 iframe 设置 src 属性

复选框值始终为打开

jQuery:如何找到第一个可见的输入/ Select /文本区域,不包括按钮?

是否可以在 beforeunload 弹出窗口中显示自定义消息?

你如何记录jQuery中一个元素触发的所有事件?

由于滚动,响应表内的 bootstrap 按钮下拉菜单不可见

如何删除集中的 contenteditable pre 周围的边框?

如何使用 jquery 更改元素类型

自调用函数前的分号?

如何在 jQuery 中取消绑定悬停?

小于 10 给数字加 0