Reputation:
How do I get the state object back that I have set with HTML5 History API:
var stateObj = { foo: "bar" };
history.pushState(stateObj, null, url);
I am trying:
$(window).bind('popstate', function(event) {
alert(event.state);
});
It comes back with undefined
.
Thanks!
Upvotes: 5
Views: 9518
Reputation: 5235
This appears to be the same problem which is discussed in the question jQuery bind popstate event not passed and answered by KSev
To summarize, since you are using jQuery, you're getting a normalized jQuery event object. The jQuery way to access the original event object is via the originalEvent
property. Therefore, you code could be rewritten as:
$(window).bind('popstate', function(event) {
alert(event.originalEvent.state);
});
You can find some additional details and examples here: stackoverflow.com/questions/7860960/popstate-returns-event-state-is-undefined
Upvotes: 1
Reputation:
I just needed to get the event.state
from the window
.
alert(window.event.state);
Upvotes: 6
Reputation: 1835
As its name implies the pop state event only fires when an event is popped from the history, not when an entry is pushed into the history.
In your example if you have two history entries, the initial entry that happens when the page loads from the server, and a second which is the one you have just pushed.
When you press the browsers back button the state that you are getting in the event is the original entry, from when the page loaded. The popstate event gives you the state that you are currently on, not the state that was just popped from the stack. Slightly confusing.
In your example if you pushed two entries into the stack, both with state data, and then hit the back button, your event handler should show you the state data of the first state you pushed into the history stack.
Upvotes: 2