2015-01-31 50 views
4

我有一个三阶段登录表单,显示/隐藏页面上的内容,因为进度已经完成。当用户从步骤1进入步骤2时,我拨打以下内容:使用history.pushState后检测浏览器后退按钮

var stateObj = { foo: "bar" }; 
history.pushState(stateObj, "", ""); 

而且我看到浏览器后退按钮启用。

现在,我试图抓住后退按钮,因此我可以相应地隐藏/显示内容(例如 - 返回到第1阶段)。

如何在这种情况下检测浏览器后退按钮?我不想让网址改变,我只是想在用户点击时调用一些JS函数。我针对的是现代桌面/移动浏览器。

+0

的[history.pushstate失败,浏览器的前进和后退按钮(可能的复制http://stackoverflow.com/questions/22751023/history-pushstate-fails-browser -back-and-forward-button) – 2016-12-05 13:05:56

回答

8

可以使用onpopstate事件。

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

欲了解更多信息,请参阅the MDN page about the onpopstate event.

+0

很酷!有没有办法为前进按钮做到这一点? – SB2055 2015-01-31 20:43:54

+1

根据文档,每当pushstate在同一文档中的两个状态之间发生更改时,都会触发该事件。后退按钮和前进按钮的状态都会改变,所以这对两者都适用。 – bigblind 2015-01-31 20:48:38

1

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

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