DEV Community

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

Posted on

9 2

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.

Tiugo image

Fast, Lean, and Fully Extensible

CKEditor 5 is built for developers who value flexibility and speed. Pick the features that matter, drop the ones that don’t and enjoy a high-performance WYSIWYG that fits into your workflow

Start now

Top comments (0)

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

Billboard image

Stick around with the Forem app — the best way to keep up with DEV and other tech communities.

AI is changing our lives. Navigate the change with community

Okay