JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Window History

14 April 2025 | Category:

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

MethodDescription
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.lengthNumber 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 entry
  • history.replaceState(state, title, url) – Replace current entry

Example:

history.pushState({}, '', '/new-page');

This changes the URL without reloading the page.


✅ Summary

TaskCode Example
Go back 1 pagehistory.back()
Go forward 1 pagehistory.forward()
Go back/forward Nhistory.go(n)
Get history lengthhistory.length