The JavaScript History object contains the browser’s history. First of all, the window part can be removed from window.history just using the history object alone works fine. The JS history object contains an array of URLs visited by the user. By using the history object, you can load previous, forward, or any particular page using various methods.
JavaScript history object Properties:
- length: It returns the length of the history URLs visited by the user in that session.
JavaScript history object Methods:
- forward(): It loads the next page. Provides the same effect as clicking back in the browser.
- back(): It loads the previous page. Provides the same effect as clicking forward in the browser.
- go(): It loads the given page number in the browser. history.go(distance) function provides the same effect as pressing the back or forward button in your browser and specifying the page exactly that you want to load.
Example 1: JavaScript code to show the working of history.back() function.
HTML
< strong > Press the back button </ strong > < input type = "button" value = "Back" onclick = "previousPage()" > < script > function previousPage() { window.history.back(); } </ script > |
Output: This example will not work if the previous page does not exist in the history list. If you click the above link then a new page opens and when you press the back button on that page it will redirect to the page that you opened previously.
Press the back button Back
Example 2: JavaScript code to show the working of history.forward() function.
HTML
< strong > Press the forward button </ strong > < input type = "button" value = "Forward" onclick = "NextPage()" > < script > function NextPage() { window.history.forward() } </ script > |
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 on your webpage. It works exactly the same as the forwarding button of your browser. If the next page doesn’t exist it will not work.
Example 3: JavaScript code to show the working of history.go() function, go(4) has the same effect as pressing your forward button four times. A negative value will move you backward through your history in a browser.go(-4) has the same effect as pressing your back button four times.
HTML
< input type = "button" value = "go" onclick = "NextPage()" > < script > function NextPage() { window.history.go(4); } </ script > |
Note: This example will not work if the next four pages do not exist in the history list.
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.