Update (2017)(更新(2017年))
Modern browsers now consider displaying a custom message to be a security hazard and it has therefore been removed from all of them.
(现代浏览器现在考虑将自定义消息显示为安全隐患,因此已将其从所有消息中删除 。)
Browsers now only display generic messages.(浏览器现在只显示通用消息。)
Since we no longer have to worry about setting the message, it is as simple as:(由于我们不再需要担心设置消息,因此它非常简单:)
// Enable navigation prompt
window.onbeforeunload = function() {
return true;
};
// Remove navigation prompt
window.onbeforeunload = null;
Read below for legacy browser support.
(请阅读下面的旧版浏览器支持。)
Update (2013)(更新(2013年))
The orginal answer is suitable for IE6-8 and FX1-3.5 (which is what we were targeting back in 2009 when it was written), but is rather out of date now and won't work in most current browsers - I've left it below for reference.
(原始答案适用于IE6-8和FX1-3.5(这是我们在2009年编写时的目标),但现在已经过时了,并且在大多数当前浏览器中都无法使用 - 我已离开它在下面供参考。)
The window.onbeforeunload
is not treated consistently by all browsers.
(所有浏览器都不一致地处理window.onbeforeunload
。)
It should be a function reference and not a string (as the original answer stated) but that will work in older browsers because the check for most of them appears to be whether anything is assigned to onbeforeunload
(including a function that returns null
).(它应该是一个函数引用而不是一个字符串(如原始答案所述),但它可以在较旧的浏览器中使用,因为对大多数浏览器的检查似乎是是否有任何内容分配给onbeforeunload
(包括一个返回null
的函数)。)
You set window.onbeforeunload
to a function reference, but in older browsers you have to set the returnValue
of the event instead of just returning a string:
(您将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;
};
You can't have that confirmOnPageExit
do the check and return null if you want the user to continue without the message.
(如果您希望用户在没有消息的情况下继续, confirmOnPageExit
执行检查并返回null。)
You still need to remove the event to reliably turn it on and off:(您仍然需要删除事件以可靠地打开和关闭它:)
// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;
// Turn it off - remove the function entirely
window.onbeforeunload = null;
Original answer (worked in 2009)(原始答案(2009年工作))
To turn it on:
(打开它:)
window.onbeforeunload = "Are you sure you want to leave?";
To turn it off:
(要关闭它:)
window.onbeforeunload = null;
Bear in mind that this isn't a normal event - you can't bind to it in the standard way.
(请记住,这不是正常事件 - 您无法以标准方式绑定它。)
To check for values?
(要检查值?)
That depends on your validation framework.(这取决于您的验证框架。)
In jQuery this could be something like (very basic example):
(在jQuery中,这可能是(非常基本的例子):)
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});