[英]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:
当用户从步骤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.
我不希望URL改变,我只想在用户回击时调用一些JS函数。 I am targeting modern desktop/mobile browsers.
我的目标是现代桌面/移动浏览器。
You can use the onpopstate
event. 您可以使用
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页面。
To detect the back button you bind to the popstate
event: 要检测后退按钮,请绑定到
popstate
事件:
$(window).bind("popstate", function(e) {
var state = e.originalEvent.state;
if ( state === null ) {
console.log("step one");
} else {
console.log(state.foo);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.