從 HTML5 開始,前端終於可以直接操作瀏覽器的歷史記錄堆疊,這也是單頁應用(SPA)能做出「有網址、能返回」體驗的基礎。
DOM 的 window.history 提供了對瀏覽器歷史記錄的讀取能力。
window.history.back(); // 等同點擊瀏覽器返回鍵 window.history.forward(); // 前進 window.history.go(-1); // 後退一頁 window.history.go(1); // 前進一頁 var numberOfEntries = window.history.length; // 堆疊中的項目總數
補充:IE 的 go() 額外支援傳入 URL 參數。
自 Gecko 2(Firefox 4)起,HTML5 引入了 history.pushState() 與 history.replaceState(),允許新增與修改 history 實體,並搭配 popstate 事件運作。
兩者的差別只有一句話:
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
執行後,網址列顯示 https://mozilla.org/bar.html,但瀏覽器不會載入 bar.html(檔案存在也不載)。接著使用者若點擊返回,網址會回到 foo.html,頁面會收到一個 popstate 事件,其 state 屬性裡是 stateObj 的一份拷本。
某種意義上,pushState() 有點像 window.location = "#foo":兩者都會建立並啟用一個關聯到目前文件的 history 實體。但 pushState 多了幾個優勢:
注意:pushState() 不會觸發 hashchange 事件,即使新舊 URL 只有 hash 部分不同。
當 history 實體被切換時會觸發 popstate。若該實體是由 pushState 或 replaceState 建立的,事件的 state 屬性會包含該實體 state 物件的一份拷本。
window.onpopstate = function (event) {
console.log("state: ", event.state);
};
頁面載入時,history 可能已經帶有一個非空 state(例如使用者關掉瀏覽器後重開)。這種情況下頁面會收到 onload 但不會收到 popstate,此時直接讀 history.state 就能拿到該物件。
實務上的典型用法是:每次 pushState 時把當前的捲動位置、頁碼、篩選條件存進 state,然後在 popstate 中還原畫面,就能做出「返回鍵可回溯操作」的 SPA。