How to redirect browser window back using JavaScript ?

In this article, we will redirect the browser window back using JavaScript. There are two approaches used to redirect the browser window back.

Approach 1: Using history.back() Method: The back() method of the window.history object is used to go back to the previous page in the current session history. In case there is no previous page, this method does not call anything. The onclick event can be specified with this method to go back one page in history.

Syntax:

history.back()

Example 1: This example uses history.back() method to redirect the browser into previous page.

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
    <script>
        function Previous() {
            window.history.back()
        }
    </script>
</head>
  
<body>
  
    <input type="button" 
           value="GoBack"
           onclick="Previous()">
  
</body>
  
</html>

chevron_right


Output:



Approach 2: Using history.go() Method: The history.go() method of the window.history object is used to load a page from the session history. It can be used to move forward or backward using the value of the delta parameter. A positive delta parameter means that the page would go forward in history. Similarly, a negative delta value would make the page go back to the previous page.
This method can be used with ‘-1’ as the delta value to go back one page in history. The onclick event can be specified with the method to go back one page in history.

Syntax:

history.ho(number\URL)

Example 2: This example uses window.history.go() method to redirect the browser into previous page.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<body>
    <button onclick="Previous()">Go Back 1 Page</button>
    <script>
        function Previous() {
            window.history.go(-1);
        }
    </script>
</body>
  
</html>

chevron_right


Output:

Note: This method will not work if the previous page does not exist in the history list.

Supported Browsers:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Apple Safari
  • Opera

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.