5

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!

3 Answers3

6

I just needed to get the event.state from the window.

 alert(window.event.state);
Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
2

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.

Oliver Nightingale
  • 2,218
  • 1
  • 16
  • 23
  • Yep, I understand that the if I am traversing to the initial page the state will be null. But this is happening for all traversals. I know pushState is firing as it is changing the URL on my ajax requests. But when I got back to a state that I have pushed I still get nothing. –  Sep 15 '11 at 09:40
  • Maybe put together a jsFiddle to recreate the issue. Using similar code I don't seem to be able to re-create the problem. – Oliver Nightingale Sep 15 '11 at 11:30
1

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

Community
  • 1
  • 1
erdomke
  • 4,072
  • 1
  • 20
  • 28