有没有办法检测用户是否使用 jquery 或 javascript 按下了刷新按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6741397/
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
Is there a way to detect if the user has pressed the refresh button using jquery or javascript?
提问by Dennis Martinez
I want to know if jquery or javascript can detect if the user has pressed the refresh button of their browser? If so can I see an example?
我想知道 jquery 或 javascript 是否可以检测用户是否按下了浏览器的刷新按钮?如果是这样,我可以看到一个例子吗?
采纳答案by Ghostoy
window.onunload event will be fired before the page is going to be refreshed.
window.onunload 事件将在页面刷新之前触发。
window.onunload = function(){
alert("unload event detected!");
}
回答by Will Mulligan
There is no way to detect if the user pressed refresh before the page refreshes, but you can use cookies to determine if the page refreshed once it loads the second time.
无法在页面刷新之前检测用户是否按下了刷新,但是您可以使用 cookie 来确定页面是否在第二次加载后刷新。
For example, each page could store the location.href
in a cookie, and if the last cookie equals the same location.href
of the current page, then the user most likely refreshed the page.
例如,每个页面都可以将location.href
cookie存储在一个 cookie 中,如果最后一个 cookielocation.href
与当前页面相同,则用户很可能刷新了该页面。
回答by Vishal Shori
Well if you are looking to detect if user press F5 or ctrl+ f5 then you can use following code :)
好吧,如果您想检测用户是否按下 F5 或 ctrl+ f5,那么您可以使用以下代码:)
$("body").keydown(function (e)
{
if (e.which == 116 || e.which == 17) {
inFormOrLink = true;
}
});
回答by GregL
I'm not sure you can do that, but what you could do instead as a hacky workaround is maybe render the referring page URL from the server into a hidden input or something, and on page load, check to see if the value of the hidden div is the same as the current URL. If it is, it must be a postback or a refresh.
我不确定你能做到这一点,但你可以做的替代方法是将来自服务器的引用页面 URL 呈现为隐藏输入或其他内容,并在页面加载时检查hidden div 与当前 URL 相同。如果是,则它必须是回发或刷新。
回答by Eman
there is 1 way to detect it.
有 1 种方法可以检测到它。
check to see if F5 was pressed. as to detect if the actual refresh was clicked, that i'm not sure if its possible, but you can check against the key code
检查是否按下了 F5。至于检测是否点击了实际刷新,我不确定是否可能,但您可以检查关键代码