HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Window History

The window.history object contains the URLs that the user has visited in the current browser window. For privacy reasons, you cannot see exactly *which* URLs are in the list, but you can use JavaScript to navigate backward and forward through them.


History Navigation Demo

These buttons simulate the standard browser "Back" and "Forward" buttons using pure JavaScript:

Total items in your session history: --

Navigating Backward

The history.back() method loads the previous URL in the history list. It works exactly like clicking the back arrow in your browser.

function goBack() {
    window.history.back();
}

Navigating Forward

The history.forward() method loads the next URL in the history list. This only works if the user has already navigated back at least once.

function goForward() {
    window.history.forward();
}

The history.go() Method

If you want to move multiple steps at once, you can use the go() method. It accepts a positive or negative integer representing how many steps to move.

// Go back 2 pages
window.history.go(-2);

// Refresh the current page
window.history.go(0);

// Go forward 1 page (same as history.forward())
window.history.go(1);
Tip: history.go(-1) is functionally identical to history.back().

The History Length

You can check how many entries are in the current session's history stack using the length property.

let entriesCount = history.length;
console.log("History entries: " + entriesCount);

History Object Methods

Method Action
history.back() Navigates to the previous page in history
history.forward() Navigates to the next page in history
history.go(n) Navigates 'n' steps forward or backward
history.length Returns the number of URLs in the history record
Privacy Note: JavaScript can only move the user through history; it cannot read the actual site names or URLs in the history list for security reasons.

Key Points to Remember

  • The History object represents the browser's session history stack.
  • It allows programmatic navigation (Back, Forward, Go).
  • It cannot be used to spy on a user's browsing history details.
  • Most methods are only useful if the user has a navigation history within the current session.
  • Modern apps (Single Page Applications) use more advanced history methods like pushState and replaceState.