The history object contains list of webpages a user navigated from the current window. It is a part of window object and can be accessed through window.history. Hence this property is specific to each browser window, tab or frame. When history is visited, the exact URL is not known due to security reasons, but it is possible to navigate forward or backward to those webpages which the user has viewed. The methods and properties of history are not standardized but all major browsers support it.
The length property gives the number of items in the history stack. This includes all the items going backward and forward in the history list. For the first tab or window or frame loaded to browser, history.length is 1. It’s maximum value is 50. This property is useful to find out the number of pages user has visited from current window or browsing session. The length property is a read only property.
Syntax for length property
var len = history.length;
The history object has following methods:
The back() method loads the previous URL from the history list. It goes back to one previous page. It is similar to back button of browser or history.go(-1). However, if there is no previous page in the history list, this method does do anything.
The forward() method navigates the page to the next URL in the history list. This is a equivalent to the history.go(1) or forward button in browser. This method will not work if there is no next page in the history list.
The go() method loads a specific URL the from history list. The method takes a number parameter which specifies the position of a page in the history list, or a string parameter which is a partial or full URL. The function goes to the first URL that matches the string. In case of a number as the input parameter, a positive number represents number of pages to go forward, while a negative number represents number of pages to go backward.
Example of the history object methods forward() and go()
Example of the history object methods back() and go()