javascript
  1. javascript-history-object

JavaScript History Object

The History object in JavaScript represents the browsing history of the current window. It allows us to navigate through the visited pages of the website, manipulate the browser’s history including forward and backward buttons using JavaScript.

Syntax

history.back(); // moves back one page in the history
history.forward(); // moves forward one page in the history
history.go(-2); // moves back two pages in the history
history.go(3); // moves forward three pages in the history

Example

Let’s take an example where we have multiple pages on our website and we want to navigate back and forth between them using the History object in JavaScript.

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

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

Output

// If you click a button after visiting a page, it will take you back to the previous page.

Explanation

In the above example, we have created a button and attached an onclick event which calls the goBack() function. When the user clicks this button, it calls the window.history.back() method which moves back one page in the browsing history.

Use

We can use the History object in JavaScript to perform the following tasks:

  • Navigating to previous/next pages in the browser history.
  • Changing the URL of the current page without reloading it.
  • Adding and modifying entries in the browsing history.
  • Storing additional data in each history entry.

Important Points

  • The History object is read-only, meaning we cannot directly modify its values.
  • We can only move forward and backward through the browser history using the History object.
  • The History object is accessible in all modern web browsers.

Summary

The History object in JavaScript represents the browsing history of the current window. It allows us to navigate through the visited pages of the website, manipulate the browser’s history including forward and backward buttons using JavaScript. We can use the History object to navigate to previous/next pages in the browser history, change the URL of the current page, and add and modify entries in the browsing history. The History object is read-only, accessible in all modern web browsers, and can only move forward and backward through the browser history.

Published on: