JS Window History

The History Object

The history property of the Window object refers to the History object, which contains the browser's session history—a list of all the pages visited in the current frame or window.

Because Window is a global object at the top of the scope chain, properties of the Window object, such as window.history, can be accessed without the window. prefix. For example, window.history.length can be simplified to history.length.

The next section will demonstrate how to retrieve information about the user's browsing history. However, due to security reasons, scripts are restricted from accessing the stored URLs.

Obtaining the Number of Pages Visited

The window.history.length property provides the count of pages in the browser's session history for the current window, including the currently loaded page.

This property enables you to determine how many pages a user has visited during the current browser session, as illustrated in the following example:

<script>
function getViews() {
alert("You've accessed " + history.length + " web pages in this session.");
}
</script>

<button type="button" onclick="getViews();">Get Views Count</button>

Returning to the Previous Page

You can utilize the back() method of the History object, i.e., history.back(), to navigate back to the previous page in the session history. This action is equivalent to clicking the browser's back button.

<script>
function goBack() {
window.history.back();
}
</script>

<button type="button" onclick="goBack();">Go Back</button>

If your browser's back button is active, clicking this Go Back link will take you one step back.


Advancing to the Next Page

You can use the forward() method of the History object, i.e., history.forward(), to move forward to the next page in the session history. This action is equivalent to clicking the browser's forward button.

<script>
function goForward() {
window.history.forward();
}
</script>

<button type="button" onclick="goForward();">Go Forward</button>

If your browser's forward button is enabled, clicking this Go Forward link will move you one step ahead.


Navigating to a Specific Page

You can also load a specific page from the browsing history using the go() method of the History object, i.e., history.go(). This method takes an integer as an argument: a negative integer moves backward in the history, and a positive integer moves forward.

window.history.go(-2);  // Go back two pages
window.history.go(-1); // Go back one page
window.history.go(0);  // Reload the current page
window.history.go(1);  // Go forward one page
window.history.go(2);  // Go forward two pages

Tip: If you try to access a page that doesn't exist in the window's history, the methods back(), forward(), and go() will not perform any action.