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:
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.
Top comments (0)