JavaScript history object methods

In JavaScript, the Browser Object Model (BOM) refers to a collection of objects provided by the browser for managing browser windows and documents. Among these, the history object is one that provides information about and operations on the browser's history.

The history object includes several methods used to control backward and forward navigation in the browser as well as retrieve information regarding the browser history. Below are some commonly used methods of the history object:

  • history.back(): Simulates a user clicking the back button in the browser, returning to the previous page.
  • history.forward(): Simulates a user clicking the forward button in the browser, navigating to the next page.
  • history.go(n): Navigates to the n-th page of the browser history, where n can be positive or negative to indicate pages ahead or behind respectively.
  • history.length: Returns the number of pages in the current browser history.

It is important to note that due to browser security restrictions, JavaScript can only operate on pages within the same origin as the current page in the browser's history. Therefore, cross-origin and other security issues must be considered during actual development.

In addition to the methods mentioned above, the history object provides others such as history.pushState() and history.replaceState(), which are used to modify information about the current page within the browser history, as well as history.scrollRestoration, which controls behavior regarding scroll restoration on pages.

// Example usage of history methods
const history = window.history;

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

// Navigate to a specific position in history (e.g., the 5th page)
history.go(5);

// Get the current number of entries in history
console.log(history.length);

// Push new state without changing URL appearance (if supported by browser configuration)
const newState = { title: 'New Page', url: '/new-page' };
history.pushState(newState, '', '/new-page');

// Replace the previous entry with a new one
history.replaceState({ title: 'Updated Title', url: '/updated-page' }, '', '/updated-page');

// Control scroll restoration behavior (e.g., disable automatic scrolling)
if ('scrollRestoration' in history) {
    history.scrollRestoration = 'none'; // Disable auto-scrolling
} else {
    console.log('Scroll restoration is not supported in this browser.');
}