The DOM Window object provides access to the browser’s session history through the history object.
Moving backward and forward through the user’s history is done using the back(), forward(), and go() methods.
Moving forward and backward
window.history.back() method in JavaScript
To move backward through history use this:
window.history.back()
The back() method loads the previous URL in the history list. This acts exactly as if the user clicked on the Back button in their browser toolbar.
How to use it?
Just add the following cod in your button.
onclick="window.history.back()"
window.history.forward() method in JavaScript
Similarly, you can move forward (as if the user clicked the Forward button), using this:
window.history.forward()
The forward() method loads the next URL in the history list.
How to use it?
Just add the following cod in your button.
onclick="window.history.forward()"
Moving to a specific point in history
go() method
The go() method loads a specific URL from the history list.
You can use the go() method to load a specific page from session history, identified by its relative position to the current page, current page’s relative position = 0.
How to use it?
window.history.go(-1)
//same as using back() method
window.history.go(1)
//same as using forward() method
For 2 it will go forward 2 pages and for -2 it will go back 2 pages.
What if you add 0?
It will refresh the current page!
We can refresh the current page by either passing 0, or by invoking it without an argument.
For example,
window.history.go(0)
window.history.go()
//both will refresh the current page
DOM history JS Methods