最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Detecting Browser Back Button after using history.pushState - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question edited Feb 6, 2018 at 9:21 Code Guru 15.6k30 gold badges143 silver badges210 bronze badges asked Jan 31, 2015 at 20:30 SB2055SB2055 12.9k37 gold badges104 silver badges205 bronze badges 1
  • Possible duplicate of history.pushstate fails browser back and forward button – Jose Gómez Commented Dec 5, 2016 at 13:05
Add a comment  | 

2 Answers 2

Reset to default 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.

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);
    }
});
发布评论

评论列表(0)

  1. 暂无评论