简体   繁体   中英

Detecting Browser Back Button after using history.pushState

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.

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.

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);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM