DEV Community

Cover image for How to navigate a browser to the previous page with JavaScript
Dillion Megida
Dillion Megida

Posted on

How to navigate a browser to the previous page with JavaScript

Direct links in web applications navigate to a specific page regardless of whatever page the user is on. But what if you wanted to navigate a user to the previous page they were on?

The back button close to the URL bar in browsers already does this:

Image description

But you can also provide a custom button to do this. Here's how...

The History API

The browser exposes the History API on the window object, which gives us access to the browser's history session. This API also gives us access to different toggling methods between different sessions in history.

history.back()

The method we need for our use case is the back() method used like this:



window.history.back()


Enter fullscreen mode Exit fullscreen mode

Calling this method moves the browser to the previous page. If there's no previous session history, the method will do nothing.

history.go()

The History API also has the go() method, which allows you to go to a specific history session. The syntax:



window.history.go(index)


Enter fullscreen mode Exit fullscreen mode

To go back one page back in the session history:



window.history.go(-1)


Enter fullscreen mode Exit fullscreen mode

To go back two pages:



window.history.go(-2)


Enter fullscreen mode Exit fullscreen mode

To go forward one page:



window.history.go(1)


Enter fullscreen mode Exit fullscreen mode

Similar to the back() method, if the target session history does not exist, the function would do nothing when called.

Top comments (0)