【问题标题】:Alert Before Page Close: How to change the Chrome's default message?页面关闭前警报:如何更改 Chrome 的默认消息?
【发布时间】:2016-06-15 00:09:25
【问题描述】:

我正在使用以下代码 sn-p 在页面关闭之前触发警报,但 Chrome 似乎忽略了该消息并显示其默认消息“您要离开此站点吗?您所做的更改可能不会被保存”。如何让 chrome 显示我的消息而不是默认消息?

window.onbeforeunload = function(e) {
    e.returnValue = "A search is in progress, do you really want to stop the search and close the tab?";
    return "A search is in progress, do you really want to stop the search and close the tab?";
}

【问题讨论】:

  • 自定义消息显示在 chromium 50
  • 浏览器供应商是否允许自定义消息会有所不同。如果他们不这样做,您将无能为力

标签: javascript jquery google-chrome


【解决方案1】:

我最近才意识到 Chrome 改变了 onbeforeunload 的行为。我找到了一种适用于主要浏览器的解决方法(在 Chrome、Firefox 和 IE 中测试,jsFiddle 出于某种原因在 Firefox 中不起作用,但我的网站可以)。使用 jQuery UI,您可以在离开页面时弹出一个对话框窗口,提供有关为什么离开当前页面会成为问题的更多信息。

window.onbeforeunload = function (e) {
    $('<div title="Warning!">A search is in progress, do you really want to stop the search and close the tab? If not, choose "Stay on page" on the browser alert.</div>').dialog({
        modal:true,
        close: function(){$(this).dialog('destroy').remove();}
    });
    return "Random message to trigger the browser's native alert.";
}

jsFiddle here

【讨论】:

    【解决方案2】:

    更新:在 Chrome 中已弃用:https://developers.google.com/web/updates/2016/04/chrome-51-deprecations?hl=en

    尝试以下方法:

    window.onbeforeunload = function (e) {
        e = e || window.event;
    
        // For IE and Firefox prior to version 4
        if (e) {
            e.returnValue = 'A search is in progress, do you really want to stop the search and close the tab?';
        }
    
        // For Safari
        return 'A search is in progress, do you really want to stop the search and close the tab?';
    };
    

    我在 Chrome 中收到的消息(自定义和默认):

    正在进行搜索,您真的要停止搜索吗? 关闭标签页?

    您确定要离开此页面吗?

    来源jsFiddle

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 2020-09-11
    • 2022-11-16
    相关资源
    最近更新 更多