【问题标题】:clear History stack of History.js清除 History.js 的历史堆栈
【发布时间】:2013-11-01 17:56:33
【问题描述】:

我在我的网页中使用History.js。它工作正常,但是当用户点击页面上的面包屑直接进入第一页时,即没有点击浏览器后退按钮,History.js 堆栈不会被清除并且noe 在第一页上按后退按钮无法正常工作。 有没有办法可以清除 History.js 堆栈。 在 Html5 历史 API 中,我会使用 history.go(-(history.length - 1));,但在使用 History.js 时,History.length 总是给我 0,即使我跟随面包屑并跳过了一些后退按钮点击。

【问题讨论】:

    标签: javascript history.js


    【解决方案1】:

    无法清除会话历史记录或禁用 来自非特权代码的后退/前进导航。最接近的可用 解决方案是 location.replace() 方法,它替换当前 具有提供的 URL 的会话历史记录项。 Mozilla Source

    有这样的解决方案:

    var Backlen=history.length;   
    
    history.go(-Backlen); // Return at the beginning
    
    window.location.replace("page url to redirect");
    

    Source

    【讨论】:

    • 我们在 History.js 中没有 history.length。我没有使用 html5 历史 API,而是使用 History.js(github.com/browserstate/history.js) 以在 html4 浏览器中兼容
    【解决方案2】:

    多诺万的回答很好,但对我来说不起作用。 backlength 索引太高,因此命令 history.go(-Backlen) 将被忽略。

    此解决方案适用于我的情况:

    var backlen = history.length - 1;  
    history.go(-backlen); // Return at the beginning
    history.replaceState({}, null, 'your relative url');
    

    【讨论】:

      【解决方案3】:

      我不知道直接答案,但你可以试试window.location.replace(url);

      引用另一篇文章: 使用 replace() 后,当前页面将不会保存在会话历史记录中,这意味着用户将无法使用后退按钮导航到它 In Javascript, how do I "clear" the back (history -1)?

      【讨论】:

        【解决方案4】:

        这是 History.js 的等价物。

        var urlPath = "index.html";
        var response = { "html": htmlpage.toString() };
        var currentIndex = History.getCurrentIndex();   
        // Return at the beginning
        if( currentIndex > 0 )
            History.go( -currentIndex ); 
        //pushState will clear forward history
        History.pushState(  response  , null, urlPath );
        

        【讨论】:

        • 在某些情况下这有效,但在其他情况下则无效。每次存在替换状态时,它都会增加索引。所以第一页是最初的帖子,如果有替换状态就是下一个索引。所以回到第一页会回到第二个索引,因为那是第一页的最后一次更新。
        猜你喜欢
        • 2020-09-10
        • 1970-01-01
        • 2020-06-04
        • 2011-02-15
        • 2010-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多