javascript 实现“此页面要求您确认要离开”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6801494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing "this page is asking you to confirm that you want to leave"
提问by Vlad Vivdovitch
This is a warning that Firefox raises when I want to leave certain pages. Based on the pages I've seen this on and that this warning appears when I try to close the page after filling in the forms, I can only assume that it's working on a dynamic page. Which technology is used to implement this functionality? How can I implement it myself on a simple hello-world page?
这是当我想离开某些页面时 Firefox 发出的警告。根据我看到的页面,并且当我在填写表单后尝试关闭页面时出现此警告,我只能假设它正在动态页面上工作。使用哪种技术来实现此功能?如何在一个简单的 hello-world 页面上自己实现它?
回答by Mrchief
You basically implement a handler for beforeunload
event. This allows you to warn your users that they have unsaved data.
您基本上为beforeunload
事件实现了一个处理程序。这允许您警告用户他们有未保存的数据。
Pseudo Code:
伪代码:
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
}
}
}
Here's a very good article that discusses this in depth: http://www.4guysfromrolla.com/webtech/100604-1.shtml
这是一篇非常好的文章,深入讨论了这一点:http: //www.4guysfromrolla.com/webtech/100604-1.shtml
Note:There is onunload
event also but that fires afterthe page has unloaded, hence is too late to take any reliable action. You should never put any criticalcode in onunload
as that is never guranteed to execute.
注意:还有一个onunload
事件,但在页面卸载后会触发,因此采取任何可靠的行动为时已晚。你永远不应该放入任何关键代码,onunload
因为它永远不会保证执行。
回答by Igoris Azanovas
Well, you need to try to add some other things like form. But something simple is:
好吧,您需要尝试添加一些其他内容,例如表单。但有一点很简单:
EDIT: Fixed HTML;
编辑:固定 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>