如何在浏览器历史记录中查找当前位置索引

时间:2015-08-14 19:58:25

标签: javascript

浏览器通过window.history对象提供客户端会话中访问过的页面列表。有了这个,客户端代码可以在列表中前后导航(使用history.back()history.forward()history.go())。

但客户端代码如何确定当前页面所在历史记录中的 where ?例如,如果客户端访问页面A,B和C,则历史记录将包含三个项目,当前历史记录项目(或状态)将用于页面C.如果用户然后单击“后退”按钮,则当前页面现在是B.然而,history.length仍然是3,反映了总共访问了三个页面的事实。我们如何确定客户当前在历史记录中的第2项?

更具体的问题是我想确定我是否位于历史记录中的第一个项目,以便我可以显示关闭页面的“关闭”按钮(假设window.opener不是空值);在历史记录中的任何其他位置,我想显示一个“后退”按钮,而不是导航到上一页。

这似乎是一个奇怪的遗漏,即历史对象中没有“当前索引”。

注意:这与question #12895940类似,但不同之处在于我真的只需要知道我是否位于历史记录的第一个位置。

2 个答案:

答案 0 :(得分:7)

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.

答案 1 :(得分:0)

要支持HTML5之前的浏览器,您可以在URL中添加查询参数,例如:mysite.com?i=0用于第一页,i=1当其导航至下一页等。

当用户单击后退按钮时,您可以使用window.location.search检索i的值,并相应地使用关闭/后退按钮来修改页面。