页面关闭前提醒:如何更改Chrome的默认消息?

我使用以下代码段在页面关闭之前触发警报,但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?"; } 

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

 window.onbeforeunload = function (e) { $('
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.
').dialog({ modal:true, close: function(){$(this).dialog('destroy').remove();} }); return "Random message to trigger the browser's native alert."; }

jsFiddle在这里

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

请尝试以下方法:

 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