如何在浏览器历史记录中查找当前位置索引 [英] How to find the current location index in the browser history

查看:173
本文介绍了如何在浏览器历史记录中查找当前位置索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()).

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

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?

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

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.

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

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.

推荐答案

我想出的唯一一件事(仅适用于HTML5 +浏览器)就是这样的:

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");
}

当页面首次加载时,会将状态对象推送到历史堆栈中。 (需要 typeof 检查以确保浏览器支持HTML5 replaceState()方法。)

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.

这篇关于如何在浏览器历史记录中查找当前位置索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆