Tutorials Tonight's Logo

WINDOW HISTORY JAVASCRIPT


The window.history object stores information about the history of the window.


Window History

The object history is a global object, so we can use it with and without referring to window, i.e window.history and history both are valid.

Browsers keep data about the history of the current window. All the pages visited are stored in a list.

The history object has some properties and methods. The following session will show you how to get information about the user's browser history.

Get Number of Pages Visited in One Session

The length property of the history object gives us the number of pages visited by the user in current the tab, including current page.

Note: We can't access the url that users visited for security purpose, but we can tell number of pages visited.

function number() {
  var num = history.length;
  document.getElementById("output").innerHTML = "You have visited " + num + "pages";
}
▶ Run the code

Output:


Window History : Going To Previous Page

The back() method of the global history object loads the previous URL to the window.

When you click the back arrow button in browse history.back() method is fired.

<button onclick="goBack()">Go Back</button>

<script>
  function goBack() {
    history.back(); // take you to previous page
  }
</script>
▶ Run the code

Output:


Window History : Going To Next Page

The forward() method of the global history object loads the next URL to the window.

When you click the next arrow button in browser history.forward() method is fired.

<button onclick="goForward()">Go to next page</button>

<script>
  function goForward() {
    history.forward(); // take you to next page
  }
</script>
▶ Run the code

Output:


Jump To Any Page From The History List

The go() method of global history objects can direct us to any number of pages from the list. The page number we want to visit is passed as an argument in the function.

The passed number can be positive, negative and zero. Zero represents the current page, negative number represents previous pages and positive number represents next pages.

See the example to understand.

history.go(0); // loads current page
history.go(-1); // loads previous page
history.go(-2); // loads 2nd previous page
history.go(1); // loads next page
history.go(2); // loads 2nd next page
▶ Run the code

Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.