JavaScript History Object

Tuesday, May 08, 2012

The JavaScript History object is an object which is accessible through the history property of a window object. It exposes useful methods and properties that let you move back and forth through the user's history.


History Object Properties

The History object has a valuable property that you can use to determine the number of items in the window's history. We can use the length property. Internet Explorer and Opera begin at 0, while Chrome, Safari, and Firefox begin at 1.


PropertyDescription
LengthGets the number of URLs in the browser's history list.


Example


<script type="text/javascript">

  document.write("URLs in history: " + history.length);

</script>


Result




History Object Methods

The History object has a valuable property that you can use to determine the number of items in the window's history. We can use the length property. Internet Explorer and Opera begin at 0, while Chrome, Safari, and Firefox begin at 1. The back() and forward() methods are identical except one is used to go back while the other is used to go forward from the items in the window history.


MethodDescription
back()Loads the previous URL from the history list.
forward()Loads the next URL from the history list.
go()Loads a specific URL from the history list.


Back() Example


<script type="text/javascript">
  function goBack(){
    window.history.back();
  }
</script>

<a href="javascript:void(0);" 
    onclick="goBack()">[Go Back!]</a>


Result


[Go Back!]


Go() Example


<script type="text/javascript">
  function goBack2(){
    window.history.go(-2);
  }
</script>

<a href="javascript:void(0);" 
    onclick="goBack2()">[Go Back Two Pages!]</a>


Result


[Go Back Two Pages!]


Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

JavaScript and jQuery: The Missing Manual HTML CSS and JavaScript Editor Professional JavaScript for Web Developers