Popstate - passing popped state to event handler

前端 未结 3 1519
误落风尘
误落风尘 2021-01-02 08:26

The following code should cause an alert of \'1\', but instead does nothing.

window.onpopstate = function(event) { alert(event.state.a) }
history.pushState({         


        
3条回答
  •  我在风中等你
    2021-01-02 08:59

    You have to modify the current state before push a new state. So, when you go back for the first state, you will get the data back:

    // updating the current state    
    window.history.replaceState({a: 1}, "First State", window.location.pathname);
    // setting the new state
    window.history.pushState({ },"Secound State", window.location.pathname);
    // getting the data back
    window.onpopstate = (event) => {
      alert(event.state.a); // Displays "1";
    }
    

提交回复
热议问题