Reputation: 68
Hi i want to detect browser refresh alone in javascript. The below code am using is detecting the browser close as well as refresh, back etc.
window.onbeforeunload = function (evt) {
var message = 'Are you sure you want to leave?';
console.log(evt);
console.log(window.event);
console.log(event);
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return evt;
}
Upvotes: 0
Views: 191
Reputation: 1075457
You can save the current time to session storage from onbeforeunload
, then when the page loads look in session storage for a time and, if you find one and it's within (say) a couple of seconds, assume it's a refresh.
window.onbeforeunload = function() {
sessionStorage.setItem("left", Date.now());
};
and elsewhere, in code that runs when the page loads:
var left = sessionStorage.getItem("left");
if (left && (Date.now() - left) < 2000) {
// Refreshed
}
Full example (live copy):
(function() {
"use strict";
window.onbeforeunload = function() {
sessionStorage.setItem("left", Date.now());
};
var left = sessionStorage.getItem("left");
if (left && (Date.now() - left) < 2000) {
// Refreshed
display("Refreshed");
} else {
// Freshly loaded
}
})();
Upvotes: 1