JavaScript History go() Tutorial

In this section, we will learn what the History go() method is and how to use it in JavaScript.

JavaScript History go() Method

The URLs that we visit via a browser window will be stored in the `history` of that browser window. The first URL is in the index 1; the second visited URL is in the index number 2 and so on.

Via the `go()` method, we can load a specific visited URL in the current browser window.

History go() Method Syntax:

history.go(value);

History go() Method Parameter:

The method takes one argument and that can be either:

  • An integer number: a positive value (for example, 2,3,4 etc.) will load the target visited URL in the forward direction. A negative value (like -1, -2 etc.) will load the visited URLs in the backward direction.

For example: let’s say via the current browser window, we’ve visited 10 URLs, and we hit the back button a couple of times and now we’re in the 5th visited URL. If we call the `go()` method and put the value 2 as its argument. That means, load the URL that is two levels ahead of the current URL (which means the one in the index number 7). But if we put a negative number (like -2) as the argument, that means load the URL that is two levels before the current loaded URL (which means the one in the index number 3).

  • Other than integer numbers, the method can take a string value as well. This value is a URL. If the URL is in the history, the browser will then load that URL.

Note: in this case, the browser navigates to the first location in history that contains the given string. The closest location may be in either backward or forward direction.

History go() Method Return Value:

The method does not return a value.

Example: JavaScript history go back

<!DOCTYPE html>
<html>
   <head>
      <title>JS is fun :)</title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      
   </head>
   <body>
    <button onclick="search()"> Go 1 page backward</button>
    <script >
      function search(){
        history.go(-1);
      }
    </script>
   </body>
</html>
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies