đ§ JavaScript history Object: Controlling the Browserâs Past

Imagine building an app like Gmail or Twitter. You click links, change sections, the URL updatesâbut the page never reloads. Thatâs the History API behind the scenes, making things smooth and snappy. Letâs dive in, one step at a time.
â
Step 1: Meet the history Object
Open your browser console and try typing:
console.log(history);
Youâll see a whole object with methods that let you jump, push, replace, and peek into the userâs browsing history.
Itâs like giving your web app its own remote control to the browserâs Back and Forward buttons.
đ Back in Time with history.back()
Say youâre on Page C, and you want to go back to Page B (just like hitting the back button):
history.back();
đ§ Try this: Navigate between a few pages, then run history.back() in the console.
See how it takes you back without clicking the back button?
đ Forward with history.forward()
If youâve gone back and want to return forward:
history.forward();
đ§Ș Try it now: Go back, then run history.forward().
đ Skip Around with history.go(n)
You want to skip backward or forward multiple steps?
history.go(-2); // Two steps back
history.go(1); // One step forward
đ§ Challenge: Try history.go(0) â What happens? (Weâll review it at the end!)
đŻ Now, Letâs Talk Single Page Apps (SPAs)
In SPAs, we donât reload the pageâbut we still want URLs to reflect state (like /dashboard, /profile, etc.).
Thatâs where pushState() and replaceState() shine.
âš history.pushState()
You add a new history entry without a full reload.
history.pushState({ page: 1 }, "Profile Page", "/profile");
đŠ Whatâs inside?
{ page: 1 }â Your custom state object (can be anything: user IDs, tab state, etc.)"Profile Page"â Optional title (not widely used)"/profile"â The new URL that appears in the address bar
đ§Ș Try it out: Copy and paste the code in your console. Notice the URL changeâno reload!
âïž history.replaceState()
This oneâs similar, but it overwrites the current entry.
history.replaceState({ page: 2 }, "Settings Page", "/settings");
Use it when you donât want users to go âBackâ to the previous state.
đ Example: Youâre auto-logging someone in after a redirectâyou replace the /login history with /dashboard.
đ§ Reacting to Changes: popstate Event
When the user hits Back or Forward in the browser, your app needs to respond. You can listen for it:
window.addEventListener("popstate", function (event) {
console.log("User navigated to: " + document.location.pathname);
console.log("State object: ", event.state);
});
đ§ Recap Cheat Sheet
| Method | What it does |
|---|---|
history.back() |
Go back one page |
history.forward() |
Go forward one page |
history.go(n) |
Move n pages in history (can be negative) |
pushState(state, title, url) |
Add a new state + update URL |
replaceState(state, title, url) |
Replace current state + URL |
popstate |
Event that fires when the user navigates |