JAVASCRIPT Tutorial

JS History

Key Concepts:

  • History Object: A built-in object that provides access to the browser's navigation history.
  • Browser History: The list of web pages visited during a browser session.
  • Back: Action to navigate back to the previous page in history.
  • Forward: Action to navigate forward to the next page in history.
  • Navigation History: The sequence of visited pages stored in the history object.

Practical Steps:

  1. Access the History Object: Use the window.history property to access the history object.
  2. Retrieve Navigation History: Access the length property to retrieve the number of pages in the history, or use the entries() method to get an array of history entries.
  3. Navigate Back/Forward: Use the back() and forward() methods to navigate backward and forward in history, respectively.
  4. Manipulate Navigation History: Use the go() method to jump to a specific entry in history, and the pushState() and replaceState() methods to add or replace entries.

Example:

// Get the current page's position in history
let historyPosition = window.history.length;

// Navigate one page back in history
window.history.back();

// Push a new entry to history
window.history.pushState({}, 'New Page', '/new-page');

// Replace the current entry in history
window.history.replaceState({}, 'Updated Page', '/updated-page');