Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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") }
));
@tdd

This comment has been minimized.

Copy link

tdd commented Feb 2, 2011

Hey Sam,

Quick question: any specific reason why you went with "hashHistory = hashHistory.slice(0, -1);" instead of just "hashHistory.pop()"?!

@sstephenson

This comment has been minimized.

Copy link
Owner Author

sstephenson commented Feb 2, 2011

Nope, that sure could be pop().

@tdd

This comment has been minimized.

Copy link

tdd commented Feb 2, 2011

Ha, good :-) I was wondering whether you had some super-intricate reason here :-) And btw, again: major props on Basecamp Mobile. I'm dying to pick your brain on the tech side of it :-)

@xu33

This comment has been minimized.

Copy link

xu33 commented May 9, 2013

There is something wrong when the history.length reach 50,it won't increase any more.

@7cc

This comment has been minimized.

Copy link

7cc commented Jun 11, 2013

a -> #b -> #a -> back

now location.hash is #b

then
forward ... console.log back
back ... console.log back

@barlas

This comment has been minimized.

Copy link

barlas commented Nov 25, 2014

really nice method to play with hashes, thanks mate !

@fabriciopa

This comment has been minimized.

Copy link

fabriciopa commented Jun 7, 2015

Works like a charm! Thanks a lot!

@N02870941

This comment has been minimized.

Copy link

N02870941 commented Dec 13, 2017

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

This comment has been minimized.

Copy link

itgoldman commented Jul 20, 2018

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
You can’t perform that action at this time.