window.history property, and is used to access the session history for that window object.
It provides useful methods and properties that let us navigate back and forth through the window's session history.
Let's take an example to see how this works to understand it better.
The History object's
back() method is used to go back to the previous URL accessed in the browser window, in the history list.
It is same as clicking the "Back button" in your browser.
<button onclick="goBack()">Go Back</button>
Similarly, we can use the history object's
forward() method to load the next URL in the history list. If next URL is not present, it does nothing.
It is same as clicking the "Forward button" in your browser.
<button onclick="goforward()">Go Forward</button>
Apart from the
go() which can be used to jump to any specific URL present in the history object.
To move to any specific page, we can use the
go() method, it takes an integer argument that works as an index value for history URL list. See the below example:
// move to one page backward
// move to two page backward
// move to one page forward
// move to two page forward
We can also use the
go() method of history object to refresh the current page. In the example below, we have called the
go() method two times and it works the same in the both scenario. We can call it anytime when we want to refresh/reload the current page.
// Refresh the page
Following are the properties of the History object. The
length property is used the most.
||specifies the number of elements contained in the object
||allows web applications to explicitly set default scroll restoration behavior on history navigation
||represents the state at the top of the history stack
Let's take an example to get number of pages visited by a user in a browser window. We will use the
length property that contains information for the visited pages. See the below example:
|specifies a method that loads the previous URL from the history list.
|specifies a method that loads the next URL from the history list.
|specifies a method that loads a specific URL from the history list.
|used to push the given data onto the session history stack with the specified title
|used to update the most recent entry on the history stack to the specified data, title, and, if provided, URL
We have explained each method with examples in the beginning of this tutorial itself.
In the next tutorial we will learn about the Navigator browser object.