JavaScript - History Object
JavaScript - History Object
Window History Object
In JavaScript, the window βhistoryβ object contains information about the browserβs session history. It contains the array of visited URLs in the current session.
The βhistoryβ object is a property of the βwindowβ object. The history property can be accessed with or without referencing its owner object, i.e., window object.
Using the βhistoryβ objectβs method, you can go to the browserβs sessionβs previous, following, or particular URL.
History Object Methods
The window history object provides useful methods that allow us to navigate back and forth in the history list.
Follow the syntax below to use the βhistoryβ object in JavaScript.
window.history.methodName();
OR
history.methodName();You may use the βwindowβ object to access the βhistoryβ object.
JavaScript History back() Method
The JavaScript back() method of the history object loads the previous URL in the history list.
Syntax
Follow the syntax below to use the history back() method.
history.back();Example
In the below codeβs output, you can click the βgo backβ button to go to the previous URL. It works as a back button of the browser.
JavaScript History forward() Method
The forward() method of the history object takes you to the next URL.
Syntax
Follow the syntax below to use the forward() method.
history.forward();Example
In the below code, click the button to go to the next URL. It works as the forward button of the browser.
JavaScript History go() Method
The go() method of the history object takes you to the specific URL of the browserβs session.
Syntax
Follow the syntax below to use the go() method.
history.go(count);In the above syntax, βcountβ is a numeric value representing which page you want to visit.
Example
In the below code, we use the go() method to move to the 2nd previous page from the current web page.
Example
In the below code, we use the go() method to move to the 2nd previous page from the current web page.
Following is the complete window history object reference including both properties and methods β
History Object Property List
The history object contains only the βlengthβ property.
PropertyDescriptionlengthIt returns the objectβs length, representing the number of URLS present in the object.
History Object Methods List
The history object contains the below 3 methods.
MethodDescriptionback()It takes you to the previous web page.forward()It takes you to the next web page.go()It can take you to a specific web page.