Popstate - passing popped state to event handler

15,479

Solution 1

Your code woudn't cause a popstate, as the pushstate command tells what page you are on NOW.

window.onpopstate = function(event) { alert(event.state.a) }
history.pushState({a: 1});
history.pushState({a: 2});
history.back()

The above code will work.
Heres the fiddle: http://jsfiddle.net/WNurW/8/

HTML5 History

As you can see on the above picture:
(1) Here you entered the page, or the fiddle, you then want to pushState, which will add a new link to the history chain.

(2) When you push state, you will add one more back click to the history, but it will also move the current place in "history" up to your new state. So going back, will not give you the history state you think you are getting, it will give the previous one.

(3) You have to go to a "new" page, or push another history state, to be able to go back to the state you created in step (2).

Solution 2

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 :)

<!DOCTYPE html>
<html>
<head>
    <title>page</title>
</head>
<body>

<script type="application/x-javascript">

function changeState(){
    history.pushState({page: 1}, "page title", "?page=1");
    history.pushState({page: 2}, "other title ", "?page=2");
    //replaceState: Updates the most recent entry on the history stack
    history.replaceState({page: 3}, "title 3", "?page=3");
    history.back(); 
    history.back(); 
    history.go(2); 
}

function showState(event){
    var restultState = JSON.stringify(event.state)
    alert("location: " + document.location + ", state: " + restultState);
}

window.onpopstate = showState;
changeState();

</script>
</body>
</html>
Share:
15,479

Related videos on Youtube

Lyn Headley
Author by

Lyn Headley

Software developer and communication scholar.

Updated on June 08, 2022

Comments

  • Lyn Headley
    Lyn Headley almost 2 years

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

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

    Fiddle: http://jsfiddle.net/WNurW/2/

    Any ideas?

  • Lyn Headley
    Lyn Headley almost 11 years
    Great explanation, love the diagram!
  • Lyn Headley
    Lyn Headley almost 11 years
    The other point I would make is that the event.state passed to popstate is not the state we just popped off, but the newly installed state.