JS history object is written as window.history. Due to security reasons, there as some limitation on the use of history object.
Methods of history object
- back() : loads the previous URL from history list of the browser.
- forward() : loads the next URL from history list of the browser.
- go() : loads the specifies URL from history list of the browser.
forward() method loads the next URL from the browser’s history list. This is same as the functioning of browser’s forward button. You can use this as follows:
<button onclick="window.history.forward()">Go Forward</button>
back() and go() methods
We can create back button using two methods:
- The back() method : This method loads the URL previous in the browser’s history list. This works same as the browser’s back button. This method does not work if previous page does not exist in the history list of browser.
<button onclick="window.history.back()">Go Back</button>
- The go() method : go() methods loads a specific URL form the browser’s list. Syntax:
The parameter passed in go() method is required. It can be a number where -1 means go back by one URL, 2 means go ahead by two URLs or a string here the function moves to the first URL that matches the string.
<p> Go back by 2: <button onclick="window.history.go(-2)">Go Back by 2</button> </p> <p> Go forward by 3: <button onclick="window.history.go(3)">Go Forward by 3</button> </p>