问题
How to know in Firefox whether refresh button is clicked or browser back button is clicked... for both events onbeforeunload() method is a callback. For IE I am handling like this:
function CallbackFunction(event) {
if (window.event) {
if (window.event.clientX < 40 && window.event.clientY < 0) {
alert("back button is clicked");
}else{
alert("refresh button is clicked");
}
}else{
// want some condition here so that I can differentiate between
// whether refresh button is clicked or back button is clicked.
}
}
<body onbeforeunload="CallbackFunction();">
But in Firefox event.clientX and event.clientY are always 0. Is there any other way to find it?
回答1:
Use for on refresh event
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};
https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload?redirectlocale=en-US&redirectslug=DOM%2Fwindow.onbeforeunload
And
$(window).unload(function() {
alert('Handler for .unload() called.');
});
回答2:
Use 'event.currentTarget.performance.navigation.type' to determine the type of navigation. This is working in IE, FF and Chrome.
function CallbackFunction(event) {
if(window.event) {
if (window.event.clientX < 40 && window.event.clientY < 0) {
alert("back button is clicked");
}else{
alert("refresh button is clicked");
}
}else{
if (event.currentTarget.performance.navigation.type == 2) {
alert("back button is clicked");
}
if (event.currentTarget.performance.navigation.type == 1) {
alert("refresh button is clicked");
}
}
}
回答3:
For Back Button in jquery // http://code.jquery.com/jquery-latest.js
jQuery(window).bind("unload", function() { //
and in html5 there is an event The event is called 'popstate'
window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
and for refresh please check Check if page gets reloaded or refreshed in Javascript
In Mozilla Client-x and client-y is inside document area https://developer.mozilla.org/en-US/docs/Web/API/event.clientX
回答4:
var keyCode = evt.keyCode;
if (keyCode==8)
alert('you pressed backspace');
if(keyCode==116)
alert('you pressed f5 to reload page')
来源:https://stackoverflow.com/questions/18457797/how-to-know-whether-refresh-button-or-browser-back-button-is-clicked-in-firefox