JavaScript Window History Object

Complete guide to browser history navigation with forward, backward, and state management

History Properties & Current State

history.length
Loading...
Number of entries in the session history, including the current page. Maximum value is 50 for security reasons.
history.state
Loading...
Current state object associated with the history entry. Returns null if no state has been set.
Current Position
Loading...
Your current position in the history stack. Calculated based on navigation actions.

History Timeline Visualization

Your Browser History Stack

Current Page Content

Page 1: History Basics
This is the initial page. Navigate using the buttons above to see history in action.

History Methods

history.back()
// Goes back one page in history
history.back();
Equivalent to: history.go(-1)
Also equivalent to: Clicking browser's back button
history.forward()
// Goes forward one page in history
history.forward();
Equivalent to: history.go(1)
Also equivalent to: Clicking browser's forward button
history.go()
// Goes to specific position
history.go(-2); // Back 2 pages
history.go(2); // Forward 2 pages
history.go(0); // Reload current
Special cases:
go(0) reloads current page
go() without parameter does nothing
history.pushState()
// Adds new state to history
history.pushState(
{page: 2}, // state object
"Page 2", // title (ignored)
"?page=2" // URL
);
Key points:
• Adds to history without reload
• State object can store data
• URL can be changed
history.replaceState()
// Replaces current history entry
history.replaceState(
{updated: true},
"Updated",
"?updated=true"
);
Key points:
• Updates current entry only
• Doesn't add to history
• Useful for updating state
// Complete History State Management Example

// 1. Store complex state objects
const userState = {
  userId: 123,
  userName: "John Doe",
  preferences: {
    theme: "dark",
    language: "en"
  },
  lastVisited: Date.now()
};

// 2. Push state with data
history.pushState(userState, "User Profile", "/profile");

// 3. Handle back/forward navigation
window.addEventListener('popstate', (event) => {
  if (event.state) {
    // Restore page based on state
    restorePageState(event.state);
  }
});

// 4. Update state without navigation
function updateUserPreference(key, value) {
  const currentState = history.state || {};
  const newState = {
    ...currentState,
    preferences: {
      ...currentState.preferences,
      [key]: value
    }
  };
  history.replaceState(newState, "");
}

Practical Examples & Navigation Flow

Navigation Flow Simulation

How to Use This Demo:

  1. Use Add New Page button to create history entries
  2. Navigate using Back and Forward buttons
  3. Try Go To... for specific navigation
  4. Update page content and save state
  5. Watch the history timeline update in real-time