现在,现代浏览器认为显示自定义消息是一种安全隐患,因此已将其从所有浏览器中删除。现在,浏览器仅显示常规消息。由于我们不再需要担心设置消息的问题,因此它很简单:
// Enable navigation prompt
window.onbeforeunload = function() {
return true;
};
// Remove navigation prompt
window.onbeforeunload = null;
原始答案适用于IE6-8和FX1-3.5(这是我们在2009年编写时所针对的目标),但是现在已经过时了,在大多数当前的浏览器中都无法使用-我已经离开了下面以供参考。
在window.onbeforeunload
所有浏览器都没有一致的处理。它应该是函数引用,而不是字符串(如原始答案所述),但是它将在较旧的浏览器中工作,因为对大多数浏览器的检查似乎是是否已分配了任何内容onbeforeunload
(包括返回的函数null
)。
您设置window.onbeforeunload
为函数引用,但是在较旧的浏览器中,您必须设置returnValue
事件的,而不仅仅是返回字符串:
var confirmOnPageExit = function (e)
{
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = 'Any text will block the navigation and display a prompt';
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
confirmOnPageExit
如果您希望用户继续操作而不收到消息,则无法进行检查并返回null。您仍然需要删除事件以可靠地打开和关闭该事件:
// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;
// Turn it off - remove the function entirely
window.onbeforeunload = null;
打开它:
window.onbeforeunload = "Are you sure you want to leave?";
要将其关闭:
window.onbeforeunload = null;
请记住,这不是正常事件-您无法以标准方式绑定到该事件。
要检查值?这取决于您的验证框架。
在jQuery中,可能类似于(非常基本的示例):
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});