H5新增了新的介面history.pushState、history.replaceState讓我們可以向history歷史記錄中新增、替換記錄,從而實現了不重新整理跳轉頁面。
在實際應用中通常會遇到這樣的需求,需要從一個目標頁跳到另一個頁面就行一些操作,操作完成再跳到目標頁,如果這時候我們還使用pushState跳轉到目標頁,就會向history中再新增一條目標頁的記錄

此時如果使用者在目標頁1中點選返回上一頁按鈕就會又重新回到操作頁,但實際想要返回到的是起始頁,這時需要連續返回3次才能到回到起始頁。如果我們在操作頁跳轉目標頁的時候使用返回上一頁history.go(-1),這時只需要點選1次返回鍵就可以回到起始頁,這樣對於使用者體驗來說更合理一些。

如果操作頁數是2頁、3頁甚至更多,只要操作頁的頁數是固定的也只需要history.go(-N)就可以了。麻煩一點的是操作頁數的數量是不固定的情況,出於安全考慮我們沒有辦法直接訪問history記錄中的具體資訊,這時候就要結合history.length來實現返回到歷史記錄中的指定頁面。
history.length儲存的是歷史記錄中的頁數,包含當前頁面。頁面的跳轉、pushState操作都會使history.length + 1。

History.go(-1)或者點選返回按鈕只會返回歷史記錄中的頁面並不會使history.length - 1。

當前頁不處在歷史記錄中最後一頁的時候跳轉頁面,會以當前頁面處在歷史記錄中的位置為基礎新增記錄並覆蓋當前頁之後的頁面記錄

新的歷史記錄會變成下邊這樣

這樣就可以利用history.lenght長度的變化來計算需要返回的頁數。在需要返回的目標頁跳轉操作的第一頁後將history.length儲存到storage中,然後操作完畢後在操作的最後一頁使用操作頁第一頁的 history.length - 操作頁最後一頁的history.length - 1,就得到了需要返回的頁數

切記不要把目標頁的history.length 作為起始頁來記錄,因為無法保證目標頁處在歷史記錄的最後一頁