In this chapter you will learn about JavaScript Window History object(window.history). The history object contains browser history.
It is not mandatory to prefix window object with history object. It can be write without window object.
There are some limitations to access history object due to privacy and security of user.
history.back() – same as when click on back button in the browser
history.forward() – same as when click on forward forward button in the browser
history.go() – allows to move more than one step backward or forward
The history.back() method is use for the previous URL from the browser History list.
This action is same as clicking on browser back button.
<html> <head> <script> function previousPage() { window.history.back() } </script> </head> <body> <input type="button" value="Click to go Back" onclick="previousPage()"> </body> </html>
Above code display a button “Click to go Back”, when click on this button, it is similar to click on a browser back button event.
The history.forward() method is use for the next URL from the browser History list.
This action is same as clicking on browser forward button.
<html> <head> <script> function nextPage() { window.history.forward() } </script> </head> <body> <input type="button" value="Click to go Forward" onclick="nextPage()"> </body> </html>
Above code display a button “Click to go Forward”, when click on this button, it is similar to click on a browser forward button event.
You can use history.go() method to go to specific page of browser history. This method accepts both positive and negative values. Current page index is set to 0.
history.go(-1);
history.go(1);
Note than history methods works only if there are entries available in browser history.
You can count the number of pages available in the history by using the value of the length property of history object.
var historyCount = window.history.length;
It is always check for history length before using other methods.