我有一个 ajax 控制的网站,其中有两种类型的页面显示给用户。为了简单起见,我们称它们为MAINPAGE和SUBPAGE。 MAINPAGE包含信息,SUBPAGE都是表单,用户可以在其中添加或修改例如MAINPAGE的现有信息。
如果我的网站被使用 HTML5 兼容浏览器的用户访问,我会在他/她浏览我的网站时使用 HistoryJS 更新 url。让我们按下面的例子:
用户进入我的网站并按以下顺序导航到以下页面,他的历史看起来像这样:
MAINPAGE(1) --> MAINPAGE(2) --> SUBPAGE(1) --> SUBPAGE(2)
当用户在 SUBPAGE(2) 上完成表单时,我想立即将他重定向到他访问的最后一个 MAINPAGE。因此,例如,当用户完成表单时,我希望用户的历史是这样的:
MAINPAGE(1) --> MAINPAGE(2)
在视觉上,我能够实现这一点,一切正常,但之后,在 HTML5 浏览器中,如果我按下浏览器上的 native 后退键,页面会尝试恢复到 SUBPAGE(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
}
最佳答案
我已经通过以下方式修改我的代码来解决这个问题:
替换了这一行:
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
}
关于javascript - 让浏览器删除特定的历史状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30665972/