Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Popstate - passing popped state to event handler

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?

like image 402
Lyn Headley Avatar asked Jul 23 '13 04:07

Lyn Headley


2 Answers

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

like image 68
André Snede Avatar answered Oct 19 '22 23:10

André Snede


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>
like image 23
felipsmartins Avatar answered Oct 20 '22 01:10

felipsmartins