Retrieve history state object after installation using the PushState history API

How can I return the state object that I set using the HTML5 history API:

var stateObj = { foo: "bar" }; history.pushState(stateObj, null, url); 

I'm trying to:

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

He returns with undefined .

Thanks!

+4
source share
3 answers

I just needed to get event.state from window .

  alert(window.event.state); 
+5
source

As the name implies, the pop state event is fired only when the event is called from the story, and not when the record is inserted into the story.

In your example, if you have two history entries, the first entry that occurs when the page is loaded from the server, and the second one that you just clicked.

When you click the back button of the browser, the state that you get in the case is the original entry, starting with the page loading. The popstate event gives you the state you are currently in, and not the state that was just popped out of the stack. A bit confusing.

In your example, if you pushed two records onto the stack, both with status data and with the "Back" button, your event handler should show you the state data of the first state that you put on the history stack.

+2
source

This is apparently the same problem that is discussed in the jQuery bind popstate event question is not passed and is answered by KSev

To summarize, since you are using jQuery, you get a normalized jQuery event object. The jQuery way to access the source event object is through the originalEvent property. Therefore, the code can be rewritten as follows:

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

You can find more information and examples here: fooobar.com/questions/208120 / ...

+1
source

All Articles