javascript 使用 history.pushState 后检测浏览器后退按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28256198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:41:11  来源:igfitidea点击:

Detecting Browser Back Button after using history.pushState

javascriptjqueryhtml

提问by SB2055

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:

我有一个三阶段登录表单,随着进度显示/隐藏页面上的内容。当用户从第 1 步进入第 2 步时,我调用以下代码:

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.

现在,我正在尝试捕捉后退按钮的点击,以便我可以相应地隐藏/显示内容(例如 - 返回到第 1 阶段)。

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.

在这种情况下如何检测浏览器后退按钮?我不希望 URL 改变,我只想在用户回击时调用一些 JS 函数。我的目标是现代桌面/移动浏览器。

回答by bigblind

You can use the onpopstateevent.

您可以使用该onpopstate事件。

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

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

有关更多信息,请参阅有关 onpopstate 事件的 MDN 页面。

回答by Ben Grimm

To detect the back button you bind to the popstateevent:

要检测绑定到popstate事件的后退按钮:

$(window).bind("popstate", function(e) {
    var state = e.originalEvent.state;
    if ( state === null ) { 
        console.log("step one");
    } else { 
        console.log(state.foo);
    }
});