History API

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

History API 透過全域性物件 history 提供對瀏覽器會話歷史記錄的訪問(請勿與 WebExtensions history 混淆)。它公開了有用的方法和屬性,讓您可以來回瀏覽使用者的歷史記錄,並操作歷史堆疊的內容。

注意: 此 API 僅在主執行緒(Window)上可用。無法在 WorkerWorklet 上下文中訪問它。

概念與用法

透過使用 back()forward()go() 方法來實現使用者歷史記錄的前進和後退。

前進和後退

向後瀏覽歷史記錄

js
history.back();

此操作與使用者點選瀏覽器工具欄上的 後退 按鈕的操作完全相同。

同樣,您可以像這樣前進(相當於使用者點選 前進 按鈕):

js
history.forward();

移動到歷史記錄中的特定位置

您可以使用 go() 方法從會話歷史記錄載入特定頁面,該頁面透過其相對於當前頁面的位置來標識。(當前頁面的相對位置為 0。)

向後移動一頁(等同於呼叫 back()

js
history.go(-1);

向前移動一頁,就像呼叫 forward() 一樣

js
history.go(1);

類似地,您可以透過傳遞 2 來前進 2 頁,依此類推。

go() 方法的另一個用途是透過傳遞 0 或不帶引數呼叫來重新整理當前頁面。

js
// The following statements
// both have the effect of
// refreshing the page
history.go(0);
history.go();

透過檢視 length 屬性的值,您可以確定歷史堆疊中的頁面數量。

js
const numberOfEntries = history.length;

介面

History

允許操作瀏覽器會話歷史記錄(即,當前頁面載入的選項卡或框架中訪問過的頁面)。

PopStateEvent

popstate 事件的介面。

示例

以下示例為 popstate 事件分配一個監聽器。然後,它說明了 history 物件的一些方法,用於在當前選項卡的瀏覽器歷史記錄中新增、替換和移動。

js
window.addEventListener("popstate", (event) => {
  alert(
    `location: ${document.location}, state: ${JSON.stringify(event.state)}`,
  );
});

history.pushState({ page: 1 }, "title 1", "?page=1");
history.pushState({ page: 2 }, "title 2", "?page=2");
history.replaceState({ page: 3 }, "title 3", "?page=3");
history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // alerts "location: http://example.com/example.html, state: null"
history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3}"

規範

規範
HTML
# the-history-interface

瀏覽器相容性

另見