Search code examples
javascriptbrowser-history

Why does the size of my window.history not decrease?


When I access the JavaScript variable window.history.length I am returned the size of my window history. As I navigate forward from one page to another and then on to another, the length of window.history increases. As I go back through my history using the browser back button, the value of window.history does not decrease even though I am moving back through the history. Why is this?


Solution

  • Think of window.history as a logically growing list or array of pages visited. Initially, there is only the initial page. When you navigate forward, a new entry is added to the end of the list and window.history.length increases by one. When you go back a page, the list does not have the entry you were previously at removed. Instead, it remains and you then have the opportunity to go forward (back to the page you just came back from).

    What this means is that you shouldn't use the length of window.history as an indicator of how far you are from the start of your browsing session. For example, if your window.history.length has a value of 5 that does not mean that if you go back 3 pages you will be at the 2nd page you visited. window.history.length represents the length of the number of pages you have visited in a forward direction but says nothing about where you currently are within that list.

    If after navigating backwards, you visit a forward page that is not the same as the previous one in the forward chain, the list will be changed and so will the length as you are now no longer able to forward visit the entries that you had previously returned from.