Skip to content

JavaScript History

The window.history object provides access to the browser’s session history, allowing navigation back and forth through the pages visited by the user in the current session.

The window.history object can be accessed directly as history (since window is the global object in browsers).

For privacy reasons, JavaScript cannot directly access the URLs in the history list. However, it can navigate through the history.

Key Methods:

  • history.back(): Loads the previous URL in the session history. Same as clicking the browser’s Back button.
  • history.forward(): Loads the next URL in the session history. Same as clicking the browser’s Forward button.
  • history.go(delta): Loads a specific URL from the session history. For example, history.go(-1) is equivalent to history.back(), history.go(1) is equivalent to history.forward(), and history.go(0) reloads the current page.

The history.length property returns the number of URLs in the session history list.

The history.back() method loads the previous URL in the history list.

<!-- HTML -->
<!-- <button id="backButton">Go Back</button> -->
<script>
const backButton = document.getElementById('backButton');
if (backButton) {
backButton.addEventListener('click', function() {
window.history.back();
});
}
</script>
<!-- To test this, you would need to navigate to this page from another page. -->

The history.forward() method loads the next URL in the history list.

<!-- HTML -->
<!-- <button id="forwardButton">Go Forward</button> -->
<script>
const forwardButton = document.getElementById('forwardButton');
if (forwardButton) {
forwardButton.addEventListener('click', function() {
window.history.forward();
});
}
</script>
<!-- To test this, you would need to go back from a page, then use this button. -->
Section titled “Navigating to a Specific Point (history.go())”

The history.go(delta) method allows navigation to a relative point in history.

<!-- HTML -->
<!-- <button id="goTwoBack">Go Two Pages Back</button> -->
<script>
const goTwoBackButton = document.getElementById('goTwoBack');
if (goTwoBackButton) {
goTwoBackButton.addEventListener('click', function() {
window.history.go(-2); // Go back two pages
});
}
</script>

Note: If there isn’t a page at the specified delta (e.g., trying to go back further than history allows), the navigation might not occur, or it might behave differently across browsers (e.g., do nothing).