Home > Articles

  • Print
  • + Share This
This chapter is from the book

Accessing Browser History

The history object is another child (property) of the window object. This object holds information about the locations (URLs) that have been visited before and after the current one, and it includes methods to go to previous or next locations.

The history object has one property you can access:

  • history.length keeps track of the length of the history list—in other words, the number of different locations that the user has visited.

The history object has three methods you can use to move through the history list:

  • history.go() opens a URL from the history list. To use this method, specify a positive or negative number in parentheses. For example, history.go(-2) is equivalent to clicking the Back button twice.

  • history.back() loads the preceding URL in the history list—equivalent to history.go(-1) or to clicking the Back button.

  • history.forward() loads the next URL in the history list, if available. This is equivalent to history.go(1) or to clicking the Forward button.

You can use the back and forward methods of the history object to add your own Back and Forward buttons to a web document. The browser already has Back and Forward buttons, of course, but sometimes it is useful (or provides a better user experience) to include your own links that serve the same purpose.

Suppose you wanted to create a script that displays Back and Forward buttons and uses these methods to navigate the browser. Here’s the code that will create the Back button:

<button type="button" onclick="history.back();">Go Back</button>

In the preceding snippet, the <button> element defines a button labeled Go Back. The onclick event handler uses the history.back() method to go to the preceding page in the browser’s history. The code for a Go Forward button is similar:

<button type="button" onclick="history.forward();">Go Forward</button>

Let’s take a look at these in the context of a complete web page. Listing 6.3 shows a complete HTML document, and Figure 6.4 shows a browser’s display of the document. After you load this document into a browser, visit other URLs and make sure the Go Back and Go Forward buttons work as expected.

LISTING 6.3 A Web Page That Uses JavaScript to Include Back and Forward Buttons

<!DOCTYPE html>

<html lang="en">
    <title>Using Custom Go Back and Go Forward Buttons</title>
    <h1>Using Custom Go Back and Go Forward Buttons</h1>
    <p>Buttons on this page allow you to go back or forward in
    your history list.</p>
    <p>These buttons should be the equivalent of the back
    and forward arrow buttons in your browser's toolbar.</p>
    <button type="button"
            onclick="history.back();">Go Back</button>
    <button type="button"
            onclick="history.forward();">Go Forward</button>

FIGURE 6.4 Showing custom Go Back and Go Forward buttons.

  • + Share This
  • 🔖 Save To Your Account