The window.history object contains the browsers history. First of all, window part can be removed from window.history just using history object alone works fine. The JS history object contains an array of URLs visited by the user. By using history object, you can load previous, forward or any particular page using various methods.
- length: It returns the length of the history URLs visited by user in that session.
- forward(): It loads the next page. Provides a same effect as clicking back in the browser.
- back(): It loads the previous page. Provides a same effect as clicking forward in the browser.
- go(): It loads the given page number in browser. history.go(distance) function provides a same effect as pressing the back or forward button in your browser and specifying the page exactly which you want to load.
Press the back button Back
Click here to see the effect of the code
Note : This example will not work if the previous page does not exist in the history list.If you click the above link then new page opens and when you press back button on that page it will redirects to that page which you opened previously.
Code #2 :
Press the forward button Forward
Note : This example will not work if the next page does not exist in the history list. This code can be used when you want to use the forward button in your webpage. It works exactly same as forwarding button of your browser. If the next page doesn’t exist it will not work.
go(4) has the same effect as pressing your forward button four times.A negative value will move you backwards through your history in a browser.go(-4) has the same effect as pressing your back button four times.
Note : This example will not work if the next four pages do not exist in the history list.
- How to get history changes notification via history.pushState() method ?
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.