By using history object we can move forward or backward by loading previous visited URL or pages.
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>