Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onpopstate, event.state == null?

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?

like image 997
mihok Avatar asked Jun 19 '12 00:06

mihok


People also ask

What is Onpopstate event?

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.

How do I dispatch Popstate event?

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.

How do you fire a Popstate event?

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


2 Answers

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.

like image 105
Jaco Briers Avatar answered Oct 06 '22 01:10

Jaco Briers


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

like image 31
MQ87 Avatar answered Oct 06 '22 01:10

MQ87