Skip to main content

JavaScript window history

The window.history object provides access to the user's browsing history in the current tab or window.

This object contains several properties and methods that can be used to navigate through the history stack, go back or forward in the history, or manipulate the URL without actually loading a new page.

Here are some of the most commonly used methods of the window.history object:

  • history.back(): navigates to the previous page in the history stack, equivalent to clicking the "Back" button in the browser.
  • history.forward(): navigates to the next page in the history stack, equivalent to clicking the "Forward" button in the browser.
  • history.go(n): navigates to a specific page in the history stack, relative to the current page. If n is a positive integer, it moves forward in the history stack by n pages; if n is a negative integer, it moves back in the history stack by -n pages.
  • history.pushState(stateObj, title, url): adds a new entry to the history stack with the specified state object, title, and URL.
  • history.replaceState(stateObj, title, url): replaces the current entry in the history stack with the specified state object, title, and URL.

Here's an example of how to use the history.back() method to go back one page in the history:

window.history.back();

In this example:

  • The back() method is called on the history object to navigate to the previous page in the history stack, equivalent to clicking the "Back" button in the browser.

You can also use the pushState() or replaceState() methods to update the URL without actually loading a new page, like this:

history.pushState({page: "home"}, "Home Page", "/home");

In this example:

  • The pushState() method is called on the history object to add a new entry to the history stack with the state object {page: "home"}, the title "Home Page", and the URL "/home".
  • This method does not actually load a new page, but it changes the URL displayed in the browser address bar and allows you to use the popstate event to detect changes in the URL and update the page content accordingly.