The history Object

Contact Us or call 1-877-932-8228
The history Object

The history Object

Like navigator, the history object is a property of the window object. For security and privacy reasons, the information you can get about the user's session history is limited to the number of entries, which you get by reading the history.length property. That's generally not so useful. However, there are a few methods of the history object, which you may indeed find useful:

history Methods
Method Description
go(int) Advanced or moves back (negative int) through the history.
back() The same as go(-1)
forward() The same as go(1)

If any of the above methods fail, no error is reported. In other words, if history.back() is called on a page that has no history, nothing at all happens.

Code Sample:

<meta charset="UTF-8">
<title>Page 1</title>
	.there {
<h1>Page 1</h1>
<h2>Table of Contents</h2>
	<li class="there">Page 1</li>
	<li><a href="history-2.html">Page 2</a></li>
	<li><a href="history-3.html">Page 3</a></li>
<button onclick="history.back();">Back</button>
<button onclick="history.forward();">Forward</button>

Code Explanation

Try this:

  1. Open NavigatorHistoryLocation/Demos/history-1.html in your browser.
  2. Click the Page 2 link.
  3. Click the Page 3 link.
  4. Now click the Back and Forward buttons several times to navigate back and forth through the pages.

If you took the above steps exactly, it should have worked as expected, but now try this:

  1. Open NavigatorHistoryLocation/Demos/history-1.html in your browser.
  2. Click the Page 3 link.
  3. Now click the Back button.

Notice it goes back from Page 3 to Page 1, which doesn't seem intuitive from the user's point of view. The problem is that the JavaScript isn't aware of the "appropriate" order of the pages as laid out in the Table of Contents. The JavaScript is just using the history object to simulate the browser's Back and Forward buttons.

As such, this makes using the history object in this way relatively useless and not recommended. In the exercise later in this lesson, we'll look at a more useful way of using the history object.