I've read several question/answers on Stack Overflow and Googled the issue, I can't seem to get the event.state
to come back with anything but null
.
I got that it wont work with the jQuery event, but when I do something like this:
window.onpopstate = function (e) { console.log(e.state) }
With something along the lines of a jQuery.ajax success calling
history.pushState({ lastUrl: data.State }, data.Title, data.UrlKey);
Neither Chrome (v19) or Firefox (v12) return anything but null? Am I missing something? Is it just not fully implemented?
The popstate event of the Window interface is fired when the active history entry changes while the user navigates the session history. It changes the current history entry to that of the last page the user visited or, if history.
A popstate event is dispatched to the window every time the active history entry changes between two history entries for the same document. If the history entry being activated was created by a call to history. pushState() or was affected by a call to history.
The popstate event of the Window interface is fired when the active history entry changes. ... The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history. back() or history. forward() in JavaScript).
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With