更新(2017)
现代浏览器现在认为显示自定义消息是一种安全隐患,因此已被removed来自他们所有人。浏览器现在仅显示通用消息。由于我们不再需要担心设置消息,所以它很简单:
// Enable navigation prompt
window.onbeforeunload = function() {
return true;
};
// Remove navigation prompt
window.onbeforeunload = null;
请阅读以下内容以了解旧版浏览器支持。
更新(2013)
最初的答案适用于 IE6-8 和 FX1-3.5(这是我们在 2009 年编写时的目标),但现在已经过时了,并且无法在大多数当前浏览器中工作 - 我已经离开下面供参考。
The window.onbeforeunload
并非所有浏览器都以一致的方式对待。它应该是一个函数引用,而不是一个字符串(如原始答案所述),但这将在较旧的浏览器中工作,因为对大多数浏览器的检查似乎是是否将任何内容分配给onbeforeunload
(包括一个返回的函数null
).
You set 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;
原始答案(2009年工作)
打开它:
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?";
});