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.
The method we need for our use case is the
back() method used like this:
Calling this method moves the browser to the previous page. If there's no previous session history, the method will do nothing.
The History API also has the
go() method, which allows you to go to a specific history session. The syntax:
To go back one page back in the session history:
To go back two pages:
To go forward one page:
Similar to the
back() method, if the target session history does not exist, the function would do nothing when called.
Top comments (0)