How to detect whether a hash change came from the Back or Forward button https://developer.mozilla.org/en-US/docs/Web/API/History_API
var detectBackOrForward = function(onBack, onForward) {
hashHistory = [window.location.hash];
historyLength = window.history.length;
return function() {
var hash = window.location.hash, length = window.history.length;
if (hashHistory.length && historyLength == length) {
if (hashHistory[hashHistory.length - 2] == hash) {
hashHistory = hashHistory.slice(0, -1);
onBack();
} else {
hashHistory.push(hash);
onForward();
}
} else {
hashHistory.push(hash);
historyLength = length;
}
}
};
window.addEventListener("hashchange", detectBackOrForward(
function() { console.log("back") },
function() { console.log("forward") }
));
if (typeof history.pushState === "function") {
window.onpopstate = function (e) {
if (e.isTrusted != undefined && e.isTrusted == true) {
console.log(e);
}
}
}
// or
window.onhashchange = function(e) {
if (window.location.hash != '#undefined') {
console.log(e);
//window.history.back();
}
};