JavaScript History Object

The History object is a predefined object in JavaScript that consists of an array of URLs, which are visited by a user in the browser.

The history object has the following features:

JavaScript History Object Properties

The following table lists the properties of the history object in JavaScript.

Property Description
length specifies the number of elements contained in the object
current specifies the URL of the current entry in the object
next specifies the URL of the next element in the History list
previous specifies the URL of the previous element in the History list

JavaScript History Object Methods

The table given below describes the methods of the history object in JavaScript.

Methods Description
back() specifies a method that loads the previous URL from the history list
forward() specifies a method that loads the next URL from the history list
go() specifies a method that loads a specific URL from the history list

JavaScript History Object Example

Here is an example demonstrates history object in JavaScript:

<!DOCTYPE HTML>
<html>
<head>
   <title>JavaScript History Object</title>
   <script type="text/javascript">
      function dispCount()
      {
         var historyCount = history.length;
         alert("Hi, you have visited " + historyCount + " web pages so far.");
      }
   </script>
</head>
<body>

<h3>JavaScript History Object Example</h3>
<form>
   <input type="button" name="history" value="My History" onclick="dispCount()">
</form>
   
</body>
</html>

Here is the output produced by the above JavaScript history object example code. This is the initial output:

javascript history object

Here is the output produced after clicking on the My History button:

javascript history object example

Let's take one more example on history object in JavaScript:

<!DOCTYPE HTML>
<html>
<head>
   <title>JavaScript History Object</title>
   <script type="text/javascript">
      function funBackward()
      {
         window.history.back()
      }
      function funForward()
      {
         window.history.forward()
      }
      function funGo()
      {
         window.history.go(1)
      }
   </script>
</head>
<body>

<h3>JavaScript History Object Example</h3>
<input type="button" id="btgo" value="Go to Next Link" onclick="funGo();">
<input type="button" id="btfo" value="Forward" onclick="funForward();">
<input type="button" id="btba" value="Backward" onclick="funBackward();">
   
</body>
</html>

Here is the sample output produced by the above JavaScript example code:

javascript history example

JavaScript Online Test


« Previous Tutorial Next Tutorial »