使浏览器删除特定的历史记录状态

4
我有一个由ajax控制的网站,其中我向用户展示两种页面。为了简单起见,我们称它们为主页面子页面主页面包含信息,而子页面则全部是表单,用户可以在其中添加或修改现有的主页面信息。

如果我的网站被一个具有HTML5兼容浏览器的用户访问,我会使用HistoryJS在他/她浏览我的网站时更新URL。让我们假设以下例子:

用户进入我的网站并按以下顺序导航到以下页面,他的历史记录看起来像这样:

主页面(1) --> 主页面(2) --> 子页面(1) --> 子页面(2)

当用户在子页面(2)上完成表单后,我希望立即将其重定向到他最后访问的主页面。例如,当用户完成表单时,我希望用户的历史记录如下:

主页面(1) --> 主页面(2)

从视觉上看,我能够实现这一点,一切都正常工作,但之后,在HTML5浏览器中,如果我按浏览器的本机返回键,则页面会尝试恢复到子页面(1),这是初始历史记录的正确后退状态。

是否可以删除一些历史状态,如果可以,如何做到这一点?

以下是我目前使用的代码:

ConverserNavigation.prototype.getPreviousMainAction = function() {
 // NOTE: the code that deals with non HTML5 compatible browsers, 
 // was removed because everything works fine there
 var startFrom, found=false;

 if (this.HistoryJS.status==true) startFrom=History.getState().data.id;    
 // if browser is HTML5 compatible, get the current state from History object, 
 // which is a HistoryJS object

 while ((!found) && (startFrom>0)) // find the last MAINPAGE visited by user
 {
     startFrom--;
     if (this.historyData[startFrom].pageData.page != 'quickactions') found=true;   
 }



 if (this.HistoryJS.status==true) History.replaceState({id:startFrom}, this.historyData[startFrom].urlData.title, this.historyData[startFrom].urlData.url);
 // replace the current history state, with the one to where we want to revert

 this.currentNavigationId=startFrom;
 this.back(); // render the ui to navigate back to the previous page, works as intended
 for (var i=this.currentNavigationId;i<this.historyData.length;i++) delete this.historyData[i]; // delete the unused history data

}
1个回答

2

我通过以下方式修改了我的代码来解决这个问题:

将这一行替换为:

if (this.HistoryJS.status==true) History.replaceState({id:startFrom}, this.historyData[startFrom].urlData.title, this.historyData[startFrom].urlData.url);

用这个:

if (this.HistoryJS.status==true) {
    History.go(goBack); //goBack is the number of states I have to backtrack
    this.HistoryJS.manualStateChange=false; // telling the browser to not fire my own UI updating functions
    History.back(); // navigating one more state back in the History object
    History.pushState({id:startFrom}, this.historyData[startFrom].urlData.title, this.historyData[startFrom].urlData.url); // recreating the original state in the History.
    this.HistoryJS.manualStateChange=true; // restarting the UI update functions on pop or push events
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接