window.onpopstate, event.state == null?
I struggled with this same issue for many hours. Too many hours. The state-argument of onpopstate -handler was null even though I had called pushState() many times before I clicked the back-button.
I also observed that my onclick-handler which called pushState() caused the onpopstate -handler to be triggered. I believe onpopstate -handler should only get called due to user clicking on the back-button from what I read on the web. But that seemed not to be the case in my case.
Could there be a bug in the browser? Seems unlikely because I had the same or similar problem on both Chrome and FireFox. But possible. Or maybe there is a "bug in the spec" being too complicated to implement correctly. No public unit-tests showing how this should work.
Finally I arrived at a solution after which EVERYTHING started working. It was to put these two calls into my onload-handler:
pushState (myInitialState, null, href);
pushState (myInitialState, null, href);
So I have to make the same push-state() call TWICE in the onload-handler! After that my onpopstate -handler started getting arguments whose state was NOT null but a state I had previously passed as argument to pushState().
I don't really understand why it now works and why it didn't earlier when I called pushState ONLY ONCE.
I would like to understand why it works now but I already spent too much time with this getting it to work. If anybody has a reference to good example-code online which explains it that would be great.
e.state
refers to the second last state that was pushed. You need to have pushed state at least twice for e.state
to not be null
. This is because you should save the state when your site is loaded the first time and thereafter every time it changes state.
I think that this question needs a more clear explanation because the sentence "second last state that was pushed" in the other answers may lead to confusion.
When we do history.pushState we are pushing into the history stack a new State, that becomes the current one (as we can see from the navigation bar url.)
The window.onpopstate event means that the top history state is being popped out (taken away from the stack) , so the e.state will now point to the new new top state in the stack (as the navigation bar will point to the previous url).