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.onbeforeunlo
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
}
})();