我有一个由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
}