Yuri Nko
Yuri Nko

Reputation: 71

window.history.pushState() data, how and when they are retrieved?

window.history.pushState([data], 'Title', '/url');

When I set up data in here, how can I use them and what kind of data this is meant for?

Upvotes: 6

Views: 13173

Answers (2)

jlewkovich
jlewkovich

Reputation: 2775

The data object is meant to store structured data of your choosing associated with the history item, so that when the state is revisited, the application has some data available associated with it. Maybe you can save the location of the page that the user was previously viewing, or some form options they had entered but never submitted.

Browsers will call the popstate() method when a back button is fired, which will pop the most recent state pushed to the stack. Developers should add an event listener to the window object for custom handling of the popstate event (such as using the data associated with the state).

// Below function will get fired for every app-wide popstate
window.addEventListener('popstate', function(event) {
  // Can access state data using event.state.data
});

Upvotes: 8

gauravmuk
gauravmuk

Reputation: 1616

This is like a unqiue identifier to the state that is being pushed. When the time comes when you want to replaceState for that particular state, it will be helpful.

Example:

Store the state: var stateObj = { foo: "bar" }; history.pushState(stateObj, "page 2", "bar.html");

You could do this to replace the state: history.replaceState(stateObj, "page 3", "bar2.html");

Reference: https://developer.mozilla.org/en/docs/Web/API/History_API#The_pushState()_method

Upvotes: 0

Related Questions