History Object
The History Object is a part of the Browser Object Model (BOM) in JavaScript. It provides access to the browser’s session history, allowing developers to navigate backward or forward through pages visited in the current tab. It is accessible via window.history
(or simply history
) and enables web applications to control page navigation programmatically.
The History Object is commonly used for:
- Navigating backward or forward in the browser history.
- Manipulating the history stack without reloading pages (e.g., single-page applications).
- Enhancing user experience with custom navigation flows.
Key Properties of the History Object
history.length
– Returns the number of URLs in the browser’s history for the current tab.
console.log(history.length);
Key Methods of the History Object
history.back()
– Navigates to the previous page in the history stack (equivalent to clicking the browser back button).
history.back();
history.forward()
– Navigates to the next page in the history stack (equivalent to clicking the browser forward button).
history.forward();
history.go(n)
– Moves forward or backward in the history stack by n
pages.
- Positive
n
→ move forward. - Negative
n
→ move backward.
history.go(-1); // Go back 1 page
history.go(2); // Go forward 2 pages
history.pushState(state, title, url)
– Adds a new entry to the browser history stack without reloading the page.
history.pushState({ page: 1 }, "Title 1", "?page=1");
history.replaceState(state, title, url)
– Updates the current history entry without adding a new one.
history.replaceState({ page: 2 }, "Title 2", "?page=2");
Practical Examples
Navigate Backward and Forward
Provides buttons for navigating backward and forward in the browser history.
<button onclick="history.back()">Go Back</button>
<button onclick="history.forward()">Go Forward</button>
<button onclick="history.go(-2)">Go Back 2 Pages</button>
History Length
Shows how many pages are stored in the current session’s history stack.
console.log("Number of pages in history:", history.length);
Push and Replace State (Single Page App Example)
This is commonly used in single-page applications (SPA) to update the URL without reloading the page and to handle browser navigation.
// Add new history entry
history.pushState({ page: 1 }, "Page 1", "?page=1");
console.log(location.href); // URL updated to include ?page=1
// Replace current entry without adding
history.replaceState({ page: 2 }, "Page 2", "?page=2");
console.log(location.href); // URL updated to ?page=2, no new history entry added
// Listen for back/forward navigation
window.addEventListener("popstate", (event) => {
console.log("State changed:", event.state);
});