JavaScript Introduction | Browser Object Model | History Object
History Object
The history object stores browser history information as a list of documents and document states. To protect the user’s personal information, JavaScript restricts some ways of accessing this object.
Number of Entries in the History List
The length property of the history object returns the number of entries in the browser history list.
function openDocument() {
location.assign("/javascript/js_bom_history");
}
document.getElementById("text").innerHTML =
"The current browser history list contains " + history.length + " entries.";
Accessing the History List
The history object has back() and forward() methods that perform the same actions as the browser’s Back and Forward buttons. You can also use the go() method to move through the history list by the integer passed as an argument.
The following example uses the back() method to move to the immediately previous URL in the browser history list. This button behaves the same as the browser’s previous page button.
<script>
function goBack() {
window.history.back();
}
</script>
The following example uses the go() method to perform the same action as the back() method.
<script>
function go() {
window.history.go(-1);
}
</script>
As in the example above, passing -1 as an argument to the go() method makes it behave the same as the back() method.
The following example uses the forward() method to move to the immediately next URL in the browser history list. This button behaves the same as the browser’s next page button.
<script>
function goForward() {
window.history.forward();
}
</script>