The Web History API provides methods to manipulate the browser's session history — the stack of pages visited in the current tab. While standard history methods allow you to move back and forth, the modern History API allows you to **change the URL in the address bar** without reloading the page.
Interact with the buttons below to see how the URL and state object change without a page refresh:
The pushState() method adds a new entry to the browser's history stack. It takes three parameters: a state object, a title (mostly ignored), and an optional URL.
// Syntax: history.pushState(state, title, url)
window.history.pushState({ page: 1 }, "New Page", "/page-1");
The replaceState() method works exactly like pushState(), except that it modifies the **current** history entry instead of creating a new one.
// Updates current entry without adding to history
window.history.replaceState({ page: 2 }, "Updated Page", "/page-updated");
replaceState() when you want to update the URL based on a user action (like filtering a list) but don't want the "Back" button to go through every single tiny change.
When the user navigates through history (e.g., clicks the browser's back button), the window object triggers a popstate event. You can listen to this event to restore the page state.
window.onpopstate = function(event) {
if (event.state) {
console.log("Current state: ", event.state.page);
}
};
| Method | Browser Behavior |
|---|---|
history.back() |
Goes to previous URL (Same as browser back) |
history.forward() |
Goes to next URL (Same as browser forward) |
history.pushState() |
Adds new entry to history and updates URL |
history.replaceState() |
Updates current history entry and URL |