Is there a way in History.js to know when the back button was pressed

maraujop picture maraujop · Nov 21, 2011 · Viewed 12.4k times · Source

I've started to test History.js. After understanding how it works and that there is no popstate, instead there is statechange. I'm looking for a way to differ when the back button of the browser has been pressed.

The reason is that I need to know the URL before the state moved, from the one I'm going to. With the gist the project includes, only the URL we go to is looked.

I hope the solution is not to track latest URL visited in a global variable.

Thanks

Answer

ashack picture ashack · May 9, 2013

I found the solutions on github to be a bit overdone for my purposes. I created a bool that is always true except right before when I used History to change the state.

var manualStateChange = true;

History.Adapter.bind(window,'statechange',function(){
    if(manualStateChange == true){
     // BACK BUTTON WAS PRESSED
    }
    manualStateChange = true;
});

Any time I change the state programmatically, set the bool to false:

manualStateChange = false;
History.pushState(null, null, currentPath);