11

I have a three-stage login form that shows/hides content on the page as progress is made. When the user proceeds from step 1 to step 2, I call the following:

var stateObj = { foo: "bar" };
history.pushState(stateObj, "", "");

And I see the browser back button enable.

Now, I'm trying to catch the back button click so I can hide/show content (for example - back to stage 1) accordingly.

How can I detect the browser back button in this scenario? I don't want the URL to change, I just want to call some JS function when the user hits back. I am targeting modern desktop/mobile browsers.

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
SB2055
  • 12,272
  • 32
  • 97
  • 202
  • Possible duplicate of [history.pushstate fails browser back and forward button](http://stackoverflow.com/questions/22751023/history-pushstate-fails-browser-back-and-forward-button) – Jose Gómez Dec 05 '16 at 13:05

2 Answers2

17

You can use the onpopstate event.

window.onpopstate = function(event) {
  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

For more info, see the MDN page about the onpopstate event.

bigblind
  • 12,539
  • 14
  • 68
  • 123
  • 2
    According to the documentation, the event is triggered every time the pushstate changes between two states within the same document. The state changes for the back button as wel as the forward button, so this should work for both. – bigblind Jan 31 '15 at 20:48
4

To detect the back button you bind to the popstate event:

$(window).bind("popstate", function(e) {
    var state = e.originalEvent.state;
    if ( state === null ) { 
        console.log("step one");
    } else { 
        console.log(state.foo);
    }
});
Ben Grimm
  • 4,316
  • 2
  • 15
  • 24