js中能获取之前的历史状态对象吗?

use*_*993 7 javascript

当我点击后退或前进按钮并且 popstate 事件触发时,我可以获得前一个状态的状态对象吗?因为不是 e.state 提供的状态对象,而是我刚刚后退/转发的状态对象?

或者,我可以检测按下的是后退按钮还是前进按钮?

我需要这个,因为我有多个子系统,它们都需要同时使用 js 历史记录,当然,我可以在推送时保存所有子系统的状态,但是,当我弹出时,我必须将状态恢复到所有子系统这也是不需要的,因为它重置了我不需要的对象。例如

state 1 = {a:1, b:1, c:1}
push a = 2
state 2 = {a:2, b:1, c:1}
hit back button, popstate fires state 1 to me
restart a with 1, b with 1, c with 1 while I only need to restart a
Run Code Online (Sandbox Code Playgroud)

另类幻想解决方案

....
hit back button, popstate fires state 1 to me
I also get state 2 (the one I just moved away from) through some black magic
do a differential comparison between the 2 states, find out that I only need to modify a
restart a with 1
Run Code Online (Sandbox Code Playgroud)

编辑:哦,还要澄清一下,没有简单的方法可以检查页面上当前的状态 a、b 和 c (因为它比 abc 和 123 更复杂一些)

Ric*_*d J 5

答案是装饰pushState以记录应用程序中的当前状态。所以,像这样:

var app = {
    currentState: false,
    originalPushState: false,

    pushState : function(state, title, href) {
        app.currentState = state;
        app.originalPushState.call(history, state, title, href);
    },

    onPopstate : function(event) {
        var newState = event.state;
        var oldState = app.currentState;
        app.currentState = newState;

        // you now have the current state and the state you came from
    },

    init : function() {
        window.onpopstate = app.onPopstate;
        app.originalPushState = history.pushState;
        history.pushState = app.pushState;
    }
}
app.init();
Run Code Online (Sandbox Code Playgroud)

顺便说一句,popstate这很令人困惑。当您弹出常规数组时,您会得到弹出的值,而不是现在位于其末尾的值,因此从语义上讲,它有点奇怪。此外,history.state始终包含当前状态,因此event.state是多余的。我想说,设计者的奇怪选择是,如果某个东西event.popped是指向实际弹出的页面状态的指针(也许只有在与您的网站位于同一域中时才可用),则更明智。


dz9*_*902 2

onpopstate在状态更改后触发,因此您无法获取原始状态,但您可以以相反的方式执行此操作,例如拥有状态的副本和当前状态的指示器,并手动更新副本onpopstate

  • 这并不是一个真正的答案..你会如何编写这个代码? (4认同)