问题
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?
回答1:
window.onunload event will be fired before the page is going to be refreshed.
window.onunload = function(){
alert("unload event detected!");
}
回答2:
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.
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.
回答3:
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.
回答4:
there is 1 way to detect it.
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
JS Code .keypress()
回答5:
Well if you are looking to detect if user press F5 or ctrl+ f5 then you can use following code :)
$("body").keydown(function (e)
{
if (e.which == 116 || e.which == 17) {
inFormOrLink = true;
}
});
来源:https://stackoverflow.com/questions/6741397/is-there-a-way-to-detect-if-the-user-has-pressed-the-refresh-button-using-jquery