这是Firefox在我想离开某些页面时发出的警告。根据我看到的页面以及在填写表单后尝试关闭页面时出现此警告,我只能假设它在动态页面上运行。使用哪种技术来实现此功能?我如何在一个简单的hello-world页面上自己实现它?
这是Firefox在我想离开某些页面时发出的警告。根据我看到的页面以及在填写表单后尝试关闭页面时出现此警告,我只能假设它在动态页面上运行。使用哪种技术来实现此功能?我如何在一个简单的hello-world页面上自己实现它?
beforeunload
事件的处理程序。这可以让您警告用户有未保存的数据。伪代码:
window.onbeforeunload = function warnUsers()
{
if (needToConfirm)
{
// check to see if any changes to the data entry fields have been made
if(changesPresent) {
return message to display
}
else {
// no changes - return nothing
}
}
}
这是一篇深入讨论此问题的非常好的文章:http://www.4guysfromrolla.com/webtech/100604-1.shtml 注意:此链接已不存在。以下是 Wayback Machine 的备份:
https://web.archive.org/web/20211020134123/http://www.4guysfromrolla.com/webtech/100604-1.shtml
注意:还有一个onunload
事件,但它会在页面卸载后触发,因此太晚了以至于无法采取任何可靠的行动。您永远不应该在onunload
中放置任何关键代码,因为无法保证执行。
好的,你需要尝试添加一些其他的东西,比如表单。但是一些简单的东西可以是:
编辑:修复了HTML;
<html>
<head>
<script language="javascript">
function mymessage()
{
alert("This message was triggered from the onunload event");
}
</script>
</head>
<body onbeforeunload="mymessage()">
<p>close this window and watch the warning box come up!</p>
</body>
</html>
就像其他答案所说,您可以使用处理程序来处理 beforeunload
。为此,您可以使用事件监听器:
addEventListener("beforeunload", () => {
// Do things before the page is closed.
event.preventDefault();
});
event.preventDefault()
会显示一个消息,询问用户是否确认离开。您还可以执行其他操作,如自动保存,而无需显示确认消息。
根据MDN的说法,返回字符串或设置event.returnValue
以激活确认消息已被弃用。