Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 9, 2022 08:15 am GMT

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()

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)

To go back one page back in the session history:

window.history.go(-1)

To go back two pages:

window.history.go(-2)

To go forward one page:

window.history.go(1)

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


Original Link: https://dev.to/dillionmegida/how-to-navigate-a-browser-to-the-previous-page-with-javascript-bp5

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To