0

I have this:

history.pushState({id:1}, 'new title', new_url);

Now, when someone uses the browser's back button, how do I retrieve the id (1)?

$(window).bind('popstate', function(event) {
   event.state.id # gives an error
});

I tried the above (as suggested in an answer) and the error I get is "Cannot read property 'id' of undefined".

user984003
  • 23,717
  • 51
  • 158
  • 250

2 Answers2

2

Alright, I managed finally to find the answer here:

popstate returns event.state is undefined

It says:

Event is the jQuery event object, not the DOM one.

To access the DOM event object, use event.originalEvent: http://jsfiddle.net/pimvdb/un4Xk/1/.

var state = event.originalEvent.state; Remember that the state is only defined when the new state has data, so it is not available when clicking and then going back to the initial state:

initial state
link to state 1
back button to initial state (no data available)

It is, however, available when clicking, clicking another time and then going back:

initial state
link to state 1
link to state 2
back button to state 1 (data available)  
Community
  • 1
  • 1
user984003
  • 23,717
  • 51
  • 158
  • 250
2

According to MDN, you could also use:

var currentState = history.state;

Jone Polvora
  • 1,728
  • 1
  • 19
  • 27