Js History in JavaScript
? JavaScript history Object
The history object in JavaScript allows you to interact with the browser's session history (the pages visited in the current tab).
? Accessing the History Object
console.log(window.history); // or simply: history? Common History Methods
| Method | Description |
|---|---|
back() | Goes back one page in the session history |
forward() | Goes forward one page in the session history |
go(n) | Loads a specific page from the history stack (by index) |
pushState() | Adds a new entry to the history stack (manual SPA use) |
replaceState() | Replaces the current entry in the history stack |
? Examples
Go Back
history.back(); // Equivalent to clicking the browser back buttonGo Forward
history.forward();Go to a specific point
history.go(-2); // Go back 2 pageshistory.go(1); // Go forward 1 page? Length of History
console.log(history.length); // Number of URLs in the history stack? Using pushState (Advanced)
Useful for single-page applications (SPAs):
history.pushState({ page: 1 }, "Title 1", "?page=1");? Note
The history API only affects the current tab's session history.
You cannot read the actual URLs for security reasons, but you can manipulate the stack.
Would you like a simple SPA navigation demo using pushState() and popstate events?