开发者

Get history state object after setting with History API pushState

How do I get the state object back that I have set with HTML5 History API:

var stateObj = { foo: "bar开发者_如何学JAVA" };
history.pushState(stateObj, null, url);

I am trying:

$(window).bind('popstate', function(event) {
    alert(event.state);
});

It comes back with undefined.

Thanks!


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

 alert(window.event.state);


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜