javascript beforeunload 检测刷新与关闭
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11453741/
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
javascript beforeunload detect refresh versus close
提问by Ryder
Using the following function is it possible to detect which button the user has pressed the refresh button or the close button? If not is there another way?
使用以下功能是否可以检测用户按下了刷新按钮或关闭按钮的哪个按钮?如果没有,还有其他方法吗?
$(window).bind('beforeunload', function(event) {
return 'pls save ur work';
});
回答by Robin Winslow
The simple answer is no - browsers' security models do not allow you to explicitly detect in what way a user has chosen to leave your page (refresh / close / internal link / external link).
简单的答案是否定的 - 浏览器的安全模型不允许您明确检测用户选择以何种方式离开您的页面(刷新/关闭/内部链接/外部链接)。
detect refresh browser for unload/beforeunload when browser closed
It is possible - using a cookie - to check when a user loads your page whether they were previously on that site in the same session - e.g. detect if they have refreshed- but not before they refresh:
可以 - 使用 cookie - 检查用户何时加载您的页面,他们之前是否在同一会话中的该站点上 - 例如检测他们是否已刷新- 但在刷新之前不会:
Detect Browser Refresh in Javascript
Check if page gets reloaded or refreshed in Javascript
A partial and imperfect approach would be to detect whether they pressed "F5" or "Ctrl+R" or "Cmd+R" (keyboard shortcuts for refresh) just before the page unload. This will detect some refreshes, but not where the user actually clicked the refresh button.
一种部分且不完美的方法是在页面卸载之前检测他们是否按下了“F5”或“Ctrl+R”或“Cmd+R”(刷新的键盘快捷键)。这将检测一些刷新,但不会检测用户实际单击刷新按钮的位置。
(function($) {
var refreshKeyPressed = false;
var modifierPressed = false;
var f5key = 116;
var rkey = 82;
var modkey = [17, 224, 91, 93];
// Check for refresh keys
$(document).bind(
'keydown',
function(evt) {
// Check for refresh
if (evt.which == f5key || window.modifierPressed && evt.which == rkey) {
refreshKeyPressed = true;
}
// Check for modifier
if (modkey.indexOf(evt.which) >= 0) {
modifierPressed = true;
}
}
);
// Check for refresh keys
$(document).bind(
'keyup',
function(evt) {
// Check undo keys
if (evt.which == f5key || evt.which == rkey) {
refreshKeyPressed = false;
}
// Check for modifier
if (modkey.indexOf(evt.which) >= 0) {
modifierPressed = false;
}
}
);
$(window).bind('beforeunload', function(event) {
var message = "not refreshed";
if (refreshKeyPressed) {
message = "refreshed";
}
event.returnValue = message;
return message;
});
}(jQuery));
You can also detect when a link is clickedwhether the target of the link is on the same site or not: How can I detect when the user is leaving my site, not just going to a different page?
您还可以检测点击链接时链接的目标是否在同一站点上: 如何检测用户何时离开我的站点,而不仅仅是转到不同的页面?