How to find the current location index in the browser history

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.

Leave a Comment