Popstate - passing a popup state to an event handler

The following code should trigger a warning โ€œ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?

+8
javascript browser-history
source share
2 answers

Your code does not trigger a pop-up message because the pushstate command tells you which 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 in the above image:
(1) Here you entered a page or a violin, then you want to click State, which will add a new link to the history chain.

(2) When you click on a state, you will add another back-click to the story, but it will also move the current location to the โ€œstoryโ€ to your new state. Therefore, returning, will not give you the story that you think you are getting about, it will give the previous one.

(3) You need to go to the โ€œnewโ€ page or click another state of the story to return to the state created in step (2).

+10
source share

To force a trigger event to fire, you need to switch between two history entries for the same document and call the correct history method.
Calling history.pushState () or history.replaceState () simply does not raise the popstate event. Also check the history.pushState() parameters.

So you can do this:

 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) 

Something more complicated here :)

 <!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> 
+4
source share

All Articles