By using history object we can move forward or backward by loading previous visited URL or pages. This object provides browser's session history.
history.length
We will get number of URL available in our history object which we can visit. Here is the syntax to get the number.
Using the above code we can write a simple code to display number of pages in History.
<script type="text/javascript">
document.writeln("Total number of pages in History " + history.length);
</script>
This is the output of your browser history.
history.back
Browser can load the previously loaded page by using this history.back method. On uses of this back button is when we ask visitor to enter again any form data by returning to previous page. Here is the syntax
window.history.back();
You can see the uses of this in the demo code below.
history.forward
Same way from the previous page we can return to current page by using forward method. Here is the syntax
<html>
<head>
<title>Demo of History object to move back or foward in JavaScript</title>
<script type="text/javascript">
function go_fwd(){
window.history.forward();
}
function go_bck(){
window.history.back();
}
</script>
</head>
<body>
<script type="text/javascript">
document.writeln("Total number of pages in History " + history.length);
</script>
<br><br><input type=button value='forward' onClick="go_fwd()";>
<input type=button value='Back' onClick="go_bck()";>
<INPUT TYPE="button" VALUE="go -1" onClick="history.go(-1);">
<INPUT TYPE="button" VALUE="go -2" onClick="history.go(-2);">
</body>
</html>
Questions
How can you access the History object in JavaScript?
What property of the History object returns the number of entries in the history stack?
How do you navigate back to the previous page using the History object?
How do you navigate forward to the next page using the History object?
How can you load a specific page from the history stack using the History object?
What method allows you to add a new state to the history stack without triggering a page refresh?
How do you modify the current state in the history stack using the History object?
What event is triggered when the user navigates through the history stack?
Can you access the state object associated with a history entry using the History object?
How can you prevent the default back/forward navigation behavior in JavaScript?