Popstate - passing popped state to event handler

前端 未结 3 1494
误落风尘
误落风尘 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 09:07

    In order to force trigger event you needs navigates between two history entries for the same document and to call proper history method.
    Calling history.pushState() or history.replaceState() just, it not will trigger popstate event. Also, check the history.pushState() params.

    So you can to do it:

    window.onpopstate = function(event) { alert(event.state.a) }
    history.pushState({a: 1}, "")
    history.back() //add history entry
    history.back() //add history entry
    history.go(1)
    

    Here something more elaborate :)

    
    
    
        page
    
    
    
    
    
    
    

提交回复
热议问题