简体   繁体   English

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

[英]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.

相关问题 history.pushstate使浏览器后退和前进按钮失败 - history.pushstate fails browser back and forward button 使用AJAX / jQuery加载页面和history.pushState()方法保留浏览器“后退”按钮功能 - preserving browser “back” button functionality using AJAX/jQuery to load pages and history.pushState() method 在ReactJs中使用history.pushState()时,后退按钮不起作用 - Back button is not working when using history.pushState() in ReactJs 前进按钮在 history.pushState 后不起作用 - Forward button not working after history.pushState 在History.pushState()之后,浏览器的后退和前进按钮不起作用 - Browser's Back & Forward Buttons Don't Work After History.pushState() 如何将history.pushState与浏览器的后退功能结合使用 - How to use history.pushState in conjunction with back functionality of the browser 前 HTML 在 history.pushState() 之后不会使用后退按钮呈现 - previous HTML won't render with back button after history.pushState() 在 JS 中使用 history.pushState 加载页面时后退按钮不起作用 - Back Button not work when load page using history.pushState in JS 使用带有history.pushstate和popstate的后退按钮时如何触发更改? - How to trigger change when using the back button with history.pushstate and popstate? 在history.pushState之后导航时恢复原始页面 - Restore original page when navigating back after history.pushState
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM