The JavaScript History object is an object which is accessible through the history property of a window object. It exposes useful methods and properties that let you move back and forth through the user’s history.
History Object Properties
The History object has a valuable property that you can use to determine the number of items in the window’s history. We can use the length
property. Internet Explorer and Opera begin at 0, while Chrome, Safari, and Firefox begin at 1.
Property | Description |
---|---|
Length | Gets the number of URLs in the browser’s history list. |
Example
<script type="text/javascript">
document.write("URLs in history: " + history.length);
</script>
History Object Methods
The History object has a valuable property that you can use to determine the number of items in the window’s history. We can use the length
property. Internet Explorer and Opera begin at 0, while Chrome, Safari, and Firefox begin at 1.
The back()
and forward()
methods are identical except one is used to go back while the other is used to go forward from the items in the window history.
Method | Description |
---|---|
back() | Loads the previous URL from the history list. |
forward() | Loads the next URL from the history list. |
go() | Loads a specific URL from the history list. |
Back() Example
<script type="text/javascript">
function goBack(){
window.history.back();
}
</script>
<a href="javascript:void(0);" onclick="goBack()">
[Go Back!]
</a>
Go() Example
<script type="text/javascript">
function goBack2(){
window.history.go(-2);
}
</script>
<a href="javascript:void(0);" onclick="goBack2()">
[Go Back Two Pages!]
</a>