Skip to content

Instantly share code, notes, and snippets.

@sstephenson
Created December 13, 2010 21:55
Show Gist options
  • Save sstephenson/739659 to your computer and use it in GitHub Desktop.
Save sstephenson/739659 to your computer and use it in GitHub Desktop.
How to detect whether a hash change came from the Back or Forward button
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") }
));
@N02870941
Copy link

Beautiful, thanks so much. I am writing an angular app, and all that ui.router stuff is so complicated, This is literally all I needed! I know I shouldn't be mixing frameworks, etc, but it was too painful. Thanks!!

@itgoldman
Copy link

as mentioned by 7cc, this fails: a -> #b -> #a -> back
it also fails if you refresh the page in the middle of history and then press forward or back. this is because you can't tell index of your current history within the actual browser history array - therefore can't tell if next hashchange is forward or backwards (even if all hashes are unique).
so my conclusion: this is a problem impossible to solve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment