History API
The History API provides access to the browser's session history (the pages visited in the tab or frame that the current page is loaded in). It allows you to manipulate the browser's URL bar without triggering a full page reload, which is the backbone of modern Single Page Applications (SPAs).
1. Navigation Methods
You can move through the user's history programmatically.
history.back(): Go to the previous page (same as clicking the browser's Back button).history.forward(): Go to the next page (same as clicking Forward).history.go(n): Go forward or backward bynpages.
history.back(); // Go back 1
history.forward(); // Go forward 1
history.go(-2); // Go back 2 pages
2. Manipulating History
The real power comes from pushState and replaceState.
pushState()
Adds a new entry to the browser's history stack. The URL changes, but the browser does not load the page.
Syntax: history.pushState(state, unused, url)
const state = { page_id: 1, user_id: 5 };
const url = "page1.html";
history.pushState(state, "", url);
replaceState()
Modifies the current history entry instead of creating a new one. Useful for updating the URL after an action (like applying a filter) without cluttering the "Back" button history.
const state = { page_id: 1, filter: "active" };
history.replaceState(state, "", "page1.html?filter=active");
3. The popstate Event
The popstate event is fired when the active history entry changes (e.g., user clicks Back or Forward).
Note: Calling pushState() or replaceState() does not trigger a popstate event. It is only triggered by browser actions (Back/Forward buttons) or history.back()/history.go().
window.addEventListener('popstate', (event) => {
console.log("Location: " + document.location + ", state: " + JSON.stringify(event.state));
// Handle the navigation (e.g., load content via AJAX based on event.state)
if (event.state) {
loadPage(event.state.page_id);
}
});
programming/javascript/vanilla/javascript programming/javascript/vanilla/events programming/javascript/vanilla/ajax-fetch