← Back to JavaScript Course | Chapter 11: Browser Object Model | Lesson 4 of 6

JS History Object

window.history is like the back button trail on a hiking map: it remembers every stop you made so you can retrace your steps, and modern apps can even quietly redraw the trail markers without actually walking anywhere.

What Is the History Object?

window.history gives script access to the browser's session history for the current tab, letting you move backward and forward through pages the user has visited without a manual click on the browser's own back/forward buttons.

Example: What Is the History Object?

javascript
console.log(history.length); // number of entries in this tab's session history
// history.back();
// history.forward();

Basic Navigation Methods

history.back() and history.forward() move one step in either direction through history, equivalent to the browser's back/forward buttons, while history.go(n) can jump multiple steps at once (history.go(-2) goes back two pages).

Example: Basic Navigation Methods

javascript
// history.back();     // like clicking the browser's back button
// history.forward();  // like clicking forward
// history.go(-2);      // jump back two pages
console.log(history.length);

Checking History Length

history.length reports how many entries exist in the session history stack, though for privacy reasons you can't read the actual URLs of those entries, only the count.

Example: Checking History Length

javascript
console.log(history.length); // count only, URLs are private

pushState for SPA Navigation

history.pushState(state, title, url) adds a new entry to history and changes the visible URL without triggering a page reload, which is the core mechanism single-page apps use to make client-side route changes look like real navigation.

Example: pushState for SPA Navigation

javascript
history.pushState({ page: 1 }, "", "?page=1"); // URL changes, no reload
console.log(location.search);

replaceState and the popstate Event

history.replaceState() works like pushState but overwrites the current entry instead of adding a new one, useful for correcting a URL without adding a back-button step. The popstate event fires when the user navigates via back/forward, letting an SPA re-render the right view for whatever URL history.pushState previously recorded.

Example: replaceState and the popstate Event

javascript
history.replaceState({ page: 2 }, "", "?page=2"); // overwrites current entry
window.addEventListener("popstate", (e) => console.log("Navigated:", e.state));
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.