browser history

browser historySkill Level: Intermediate
Skills Required: Objects and Basic JavaScript

Abstract:

JavaScript can gracefully handle all objects that exist in an HTML document. This includes window, document, links, images and even plugins. Today we will see how to manipulate the web browser history.

The History Object:

JavaScript’s history object represents the web browser history (i.e., previously visited links, etc.). One interesting property of this object, namely length, gives the number of previously visited URL’s in the browser’s history. The methods available to us are discussed below. But first take a look at using the length property:

function checkHistory ()
{
var length = history.length;
alert ("You have visited " + length + " sites, so far");
}

Methods:

The history object exposes the following methods:

  • history.back()
  • history.forward()
  • history.go (where)

The first method is used to go back to the last page. The effect is same as pressing the browser’s back button. Similarly, the forward() method moves to next page. The effect is similar to pressing the browser’s forward button.

The last method is interesting; the where argument can be a positive or negative number that specifies how far we wish to move in the history. A positive number, +5, indicates move forward 5 URLs while a negative number, -1, means go back 1 URL.

An Example:

The following rather simple example demonstrates the three methods of history object. It creates three buttons and one text box. The first button, labeled “<-Back”, goes back while the second button labeled “Forward->” moves forward. The third button labeled “Go” moves to the number specified in the text box.

<html>
<head>
<title>History Object Example</title>


function move()
{
var number = parseInt(document.example.skip.value);
history.go (number);
}

</head>

<body>
<form name="example">
<input type= "button" value="<-Back" onClick="history.back()">
<input type= "button" value="Forward->" onClick="history.forward()"><br>
<input type="text" name="skip" size="3">
<input type="button" value="Go" onClick="move()">
</form>
</body>
</html>

Last Words:

Questions, comments and suggestions can be posted in discussions area.

Leave a Reply

Your email address will not be published.