Make browser go back to previous page using JavaScript

OpenJavaScript 0
Reading Time: 2 minutes 🕑

Last updated: March 5, 2022.

There are two ways to go back to the previous page in a user’s browser history using JavaScript.

history.back() makes the browser go back one page. Here is how you can use it to create a ‘back to previous page’ button:

<button id="goBack">Back to previous page</button>

<script>
const goBack =  document.getElementById('goBack');
goBack.addEventListener('click', () => { history.back() } )
</script>

This will go back one page in the user’s browser history. If there is no previous page to go back to, nothing will happen when the button is clicked.

Alternatively, the history.go() method can be used. This method accepts a negative or positive number representing how many pages to go backwards or forwards.

To go back by one page in the browser, use history.go(-1):

<button id="goBack">Back to previous page</button>

<script>
const goBack =  document.getElementById('goBack');
goBack.addEventListener('click', () => { history.go(-1) } )
</script>

Going back more than one page

With history.go, it is possible to backwards more than one page by entering a negative number greater than -1.

For example, the following button navigates backwards two pages in the user’s history:

<button id="goBack">Back to two pages</button>

<script>
const goBack =  document.getElementById('goBack');
goBack.addEventListener('click', () => { history.go(-2) } )
</script>

If this history does not exist in the browser, nothing happens.

Going forward by one page or more

It is also possible to create a button that will go forwards in a browser’s history.

To go forwards by one page, use history.forward or history.go(1):

<button id="goForward">Return to next page</button>

<script>
const goForward = document.getElementById('goForward');
goForward.addEventListener('click', () => { history.forward() /* or 'history.go(1)' */ } )
</script>

To go forwards by multiple pages, use history.go() with a positive number greater than one:

<button id="goForward">Go forward two pages</button>

<script>
const goForward = document.getElementById('goForward');
goForward.addEventListener('click', () => { history.go(2) } )
</script>

Summary

MethodActionUsage example
history.back()Goes back by one page in user’s browser historyhistory.back() – back one page
history.forward()Goes forward by one page in user’s browser historyhistory.forward() – forward one page
history.go()Navigates user’s browser history according to number passed inhistory.go(-2) – back two pages

Related links