HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

Web History API

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.


State Navigation Lab

Interact with the buttons below to see how the URL and state object change without a page refresh:

History Action Logs:
Waiting for interaction...
Note: Browsers prevent you from pushing URLs that belong to a different domain for security reasons.

Using pushState()

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");

Using replaceState()

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");
Tip: Use 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.

The popstate Event

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);
    }
};

History API Methods Summary

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

Key Points to Remember

  • The History API is the foundation of Single Page Applications (SPAs).
  • pushState() creates a new history record.
  • replaceState() overwrites the current record.
  • Neither method triggers a **page reload**.
  • The popstate event fires when the back/forward buttons are used.
  • URLs passed to these methods must have the same **origin** (domain).