使用 javascript 处理刷新页面事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3950029/
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
Handle refresh page event with javascript
提问by tiboo
Is it possible to use javascript to handle the event of refreshing page? What i want is get notice if user do one of these behaviours:
是否可以使用javascript来处理刷新页面的事件?如果用户执行以下行为之一,我想要的是得到通知:
- refresh page by pressing F5
- close tab or browser
- enter a new url then press enter on browser
- 按F5刷新页面
- 关闭选项卡或浏览器
- 输入一个新的网址,然后在浏览器上按回车键
to display a warning message?
Thanks in advance!
显示警告信息?
提前致谢!
回答by Lou Franco
You don't want the refresh, you want the onbeforeunload event.
你不想要刷新,你想要 onbeforeunload 事件。
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
Sample code from article
文章中的示例代码
<HTML>
<head>
<script>
function closeIt()
{
return "Any string value here forces a dialog box to \n" +
"appear before closing the window.";
}
window.onbeforeunload = closeIt;
</script>
</head>
<body>
<a href="http://www.microsoft.com">Click here to navigate to
www.microsoft.com</a>
</body>
</html>
回答by Darin Dimitrov
The closest you could get is the window.onbeforeunloadevent:
最接近的是window.onbeforeunload事件:
window.onbeforeunload = function (e) {
var e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = 'Leaving the page';
}
// For Safari
return 'Leaving the page';
};
It is important to note that you need to return a string from this function.
需要注意的是,您需要从此函数返回一个字符串,这一点很重要。