Reputation: 12204
Browsers provide a list of the pages visited within a client session through the window.history
object. With this, client code can navigate forwards and backwards through the list (using history.back()
, history.forward()
, and history.go()
).
But how can the client code determine where in the history the current page is located? For example, if the client visits pages A, B, and C, the history will contain three items, and the current history item (or state) will be for page C. If the user then clicks the 'back' button, the current page is now B. However, the history.length
is still 3, reflecting the fact that three pages were visited in total. How do we determine that the client is currently at item 2 in the history?
A more specific problem is that I want to determine if I am positioned at the first item in the history, so that I can display a 'Close' button which will close the page (assuming that window.opener
is not null); at any other position in the history, I want to display a 'Back' button instead which will navigate to the previous page.
This seems to be a curious omission that there is no 'current index' into the history object.
Note: This is similar to question #12895940, but differs in that I really only need to know if I am positioned at the first location in the history.
Upvotes: 31
Views: 13208
Reputation: 115
To support pre HTML5 browsers you can add a query parameter to the url, for example: mysite.com?i=0
for the first page, i=1
when they navigate to the next page etc.
When the user hits the back button, you can retrieve the value of i with window.location.search
and modify your page with a close/back button accordingly.
Upvotes: 1
Reputation: 12204
The only thing I came up with (which only works in HTML5+ browsers) is something along the lines of this:
// Onload
{
if (!history.state && typeof(history.replaceState) == "function")
history.replaceState({ page: history.length, href: location.href }, "foo");
}
This pushes a state object onto the history stack when the page first loads. (The typeof
check is needed to ensure that the browser supports the HTML5 replaceState()
method.)
Later, I can check if the current history object is the first one in the list that got replaced:
if (history.state && history.state.page == 1) {
// It appears that we are positioned at the first history item
...
}
This seems to be adequate for what I need.
Upvotes: 16