搜索

首页  >  问答  >  正文

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

<p>使用<code>window.onbeforeunload</code>(或<code>$(window).on("beforeunload")</code>)时,是否可以在该弹出窗口中显示自定义消息?< /p> <p>也许是一个适用于主要浏览器的小技巧?</p> <p>通过查看现有的答案,我觉得过去使用诸如 <code>confirm</code> 或 <code>alert</code> 或 <code>event.returnValue</code> 之类的东西是可能的,但现在看来他们不再工作了。</p> <p>那么,如何在 beforeunload 弹出窗口中显示自定义消息?这甚至/仍然可能吗?</p>
P粉478445671P粉478445671540 天前647

全部回复(2)我来回复

  • P粉186904731

    P粉1869047312023-08-25 00:34:09

    不再是了。所有主要浏览器都开始忽略实际消息并只显示自己的消息。

    正确。 很久以前,您可以使用confirmalert,最近您可以从onbeforeunload返回一个字符串处理程序并且该字符串将被显示。现在,字符串的内容将被忽略,并将其视为标志。

    当使用 jQuery 的 on 时,您确实必须在原始事件上使用 returnValue

    $(window).on("beforeunload", function(e) {
        // Your message won't get displayed by modern browsers; the browser's built-in
        // one will be instead. But for older browsers, best to include an actual
        // message instead of just "x" or similar.
        return e.originalEvent.returnValue = "Your message here";
    });

    或者老式的方式:

    window.onbeforeunload = function() {
        return "Your message here"; // Probably won't be shown, see note above
    };

    这就是你所能做的。

    回复
    0
  • P粉143640496

    P粉1436404962023-08-25 00:32:48

    tl;dr - 在大多数现代浏览器中您无法再设置自定义消息

    为了在用户关闭窗口之前设置确认消息,您可以使用

    jQuery

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

    Javascript

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

          重要的是要注意,您不能 确认/警报 内部 beforeunload< /代码>


    以下是使用我有权访问的浏览器的结果:

    Chrome:

    火狐浏览器:

    Safari:

    IE:

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

    1. Chrome 在版本 51 中删除了对自定义消息的支持
    2. Opera 在版本 38 中删除了对自定义消息的支持
    3. Firefox 在 44.0 版本中删除了对自定义消息的支持(仍在寻找此信息的来源)
    4. Safari 在版本 9.1 中删除了对自定义消息的支持

    回复
    0
  • 取消回复