The History Object In JavaScript

The history object is also part of the window object and it provides information about the browser history of the current window.

The history object has only one property which is called length. The lenght property returns the number of pages in the session history of the browser for the current window (including the currently loaded page).


alert("You viewed " + history.length + " page(s).");

Methods of the History Object

The table below shows the three methods available for the history object.

MethodPurpose
back()Sends the browser window one page back in the history list.
forward()Sends the browser window one page forward in the history list.
go()Sends the browser to a specified page in the history list using an integer value.

The back() Method

The back() method sends the browser to the last page visited in the history list before the current page. It is similar to the browser “back” button.


<form>
<input type="button" value="Back" id="go-back" />
</form>

<script type="text/javascript">
var BackButton = document.getElementById("go-back");
BackButton.onclick = function() {
history.back();
}
</script>

The forward() Method

The forward() method sends the browser to the page visited in the history list after the current page.
To use it you call the method in the script where desired. As example, let’s update the previous script with a forward button:


<form>
<input type="button" value="Back" id="go-back" />
<input type="button" value="Forward" id="go-forward" />
</form>

<script type="text/javascript">
var BackButton = document.getElementById("go-back");
var ForwardButton = document.getElementById("go-forward");
BackButton.onclick = function() {
history.back();
}
ForwardButton.onclick = function() {
history.forward();
}
</script>

The go() Method

The go() method takes in an integer as a parameter.
The integer can be a positive number to go forward in the history list or a negative number to go back in the history list.


history.go(3);

The above code will go forward three pages in the window’s history.


history.go(-4);

The above code will go back four pages in the window’s history.

Leave a Reply