History Object in Javascript
The window.history
object stores information about the history of the window.
Window History
history is a global object, so we can use it with and without referring to the window, i.e window.history
and history
both are valid.
Browsers keep data about the history of the current window. All the pages visited are stored in a list.
The history object has some properties and methods. The following session will show you how to get information about the user's browser history.
Get the Number of Pages Visited in One Session
The length
property of the history
object gives us the number of pages visited by the user in current the tab, including the current page.
Note: We can't access the URL that users visited for security purposes, but we can tell the number of pages visited.
Window History: Going To the Previous Page
The back()
method of the global history
object loads the previous URL to the window.
When you click the back arrow button in browse history.back()
method is fired.
Example
<button onclick="goBack()">Go Back</button>
<script>
function goBack() {
history.back(); // take you to previous page
}
</script>
Try it
Output:
Window History: Going To Next Page
The forward()
method of the global history
object loads the next URL to the window.
When you click the next arrow button in browser history.forward()
method is fired.
Example
<button onclick="goForward()">Go to next page</button>
<script>
function goForward() {
history.forward(); // take you to next page
}
</script>
Try it
Output:
Jump To Any Page From The History List
The history.go() method can direct us to any number of pages from the list. The page number we want to visit is passed as an argument in the function.
The passed number can be positive, negative, or zero. Zero represents the current page, the negative number represents previous pages and the positive number represents the next pages.
See the example to understand.
Example
history.go(0); // loads current page
history.go(-1); // loads previous page
history.go(-2); // loads 2nd previous page
history.go(1); // loads next page
history.go(2); // loads 2nd next page
Try it