The usage of pushState and replaceState in H5
pushState and replaceState in H5 are two methods of the History object that are both used to modify the browser’s history.
The pushState method is used to add a new entry to the browser’s history without refreshing the page. It takes three parameters: state, title, and url.
- State: a JavaScript object that represents the new historical status. This object can contain any data for saving the page’s status information.
- Title: The title of the new history record, which is currently ignored by most browsers.
- URL: The URL of the new historical record, which can be a relative URL or an absolute URL.
Example:
The following is an illustration of the concept.
history.pushState({page: 1}, "Page 1", "/page1");
The code above will add a new entry into the history with the URL /page1 and the state object {page: 1}.
The replaceState method is used to replace the current history entry without refreshing the page. It takes three parameters: state, title, and url, which are the same as the parameters for the pushState method, but replaceState will replace the current history entry instead of adding a new one.
history.replaceState({page: 2}, "Page 2", "/page2");
The code above will replace the current history with a URL of /page2 and a state object of {page: 2}.
The use of pushState and replaceState methods allows for seamless page navigation and managing page states without the need for a refresh. This can be combined with the popstate event to listen for changes in the browsing history and perform corresponding actions based on the state object.