JavaScript Window History
14 April 2025 | Category: JavaScript
The window.history
object allows JavaScript to interact with the browser’s session history — i.e., the pages the user has visited in the current tab.
With this, you can:
- Navigate back and forth through history
- Move to a specific page in history
- Get the number of pages in the session
📌 What is window.history
?
The history
object is part of the Browser Object Model (BOM) and is accessible via window.history
.
You can use it to:
- Move backward/forward
- Check how many pages are in the history
- Manipulate the history stack (advanced)
🔹 Common history
Methods
Method | Description |
---|---|
history.back() | Go back one page (like browser back button) |
history.forward() | Go forward one page (like browser forward button) |
history.go(n) | Move n steps forward or backward |
history.length | Number of URLs in history stack |
🔸 Examples
✅ Go Back One Page
history.back(); // Equivalent to clicking the browser back button
✅ Go Forward One Page
history.forward(); // Like clicking the browser forward button
✅ Go to a Specific Page
history.go(-2); // Go back 2 pages
history.go(1); // Go forward 1 page
✅ Get Total History Length
console.log("History length:", history.length);
📍 Use Case: Buttons for Navigation
<button onclick="history.back()">⬅ Go Back</button>
<button onclick="history.forward()">➡ Go Forward</button>
<button onclick="history.go(-3)">⏪ Back 3 Pages</button>
⚠️ Note
- You can’t see the exact URLs in the user’s history due to security and privacy.
history.length
gives you the number of entries, not specific URLs.
🌐 Advanced: Push and Replace History (with history.pushState()
)
For single-page applications (SPAs), you can use:
history.pushState(state, title, url)
– Push a new entryhistory.replaceState(state, title, url)
– Replace current entry
Example:
history.pushState({}, '', '/new-page');
This changes the URL without reloading the page.
✅ Summary
Task | Code Example |
---|---|
Go back 1 page | history.back() |
Go forward 1 page | history.forward() |
Go back/forward N | history.go(n) |
Get history length | history.length |