window.onpopstate, event.state == null?

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