CookieStore

基線 2025 *
新推出

自 2025 年 6 月起,此功能已在最新的裝置和瀏覽器版本中可用。此功能可能不適用於舊裝置或瀏覽器。

* 此特性的某些部分可能存在不同級別的支援。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

注意:此功能在 Service Workers 中可用。

CookieStore 介面是 Cookie Store API 的一部分,它提供了從頁面或 Service Worker 非同步獲取和設定 cookie 的方法。

CookieStore 可在 WindowServiceWorkerGlobalScope 上下文中透過全域性作用域的屬性訪問。因此,它沒有建構函式。

EventTarget CookieStore

例項方法

CookieStore.delete()

delete() 方法會刪除具有給定 nameoptions 物件的 cookie。它返回一個 Promise,該 Promise 在刪除完成或沒有匹配的 cookie 時解析。

CookieStore.get()

get() 方法會獲取具有給定 nameoptions 物件的單個 cookie。它返回一個 Promise,該 Promise 會解析為單個 cookie 的詳細資訊。

CookieStore.getAll()

getAll() 方法會獲取所有匹配的 cookie。它返回一個 Promise,該 Promise 會解析為 cookie 列表。

CookieStore.set()

set() 方法使用給定的 namevalueoptions 物件來設定 cookie。它返回一個 Promise,該 Promise 在 cookie 設定完成後解析。

事件

change

當任何 cookie 被更改時,會觸發 change 事件。

示例

下面的示例可以透過將程式碼複製到測試環境中並使用 本地伺服器 執行,或將其部署到 GitHub Pages 等網站上進行測試。

設定 cookie

本示例展示瞭如何透過傳遞 namevalue 來設定 cookie,以及透過設定 options 值來設定 cookie。

cookieTest() 方法使用 namevalue 屬性設定一個 cookie,並使用 namevalueexpires 屬性設定另一個 cookie。然後,我們使用 CookieStore.get() 方法獲取每個 cookie,並將它們記錄下來。

js
async function cookieTest() {
  // Set cookie: passing name and value
  try {
    await cookieStore.set("cookie1", "cookie1-value");
  } catch (error) {
    console.log(`Error setting cookie1: ${error}`);
  }

  // Set cookie: passing options
  const day = 24 * 60 * 60 * 1000;

  try {
    await cookieStore.set({
      name: "cookie2",
      value: "cookie2-value",
      expires: Date.now() + day,
      partitioned: true,
    });
  } catch (error) {
    log(`Error setting cookie2: ${error}`);
  }

  // Get named cookies and log their properties
  const cookie1 = await cookieStore.get("cookie1");
  console.log(cookie1);

  const cookie2 = await cookieStore.get("cookie2");
  console.log(cookie2);
}

cookieTest();

獲取 cookie

本示例展示瞭如何使用 CookieStore.get() 獲取特定 cookie,或使用 CookieStore.getAll() 獲取所有 cookie。

示例程式碼首先設定三個 cookie,用於演示獲取方法。首先,它使用 CookieStore.set() 方法建立 cookie1cookie2。然後,它使用較舊的同步 Document.cookie 屬性建立第三個 cookie(以便我們展示這些 cookie 也可以使用 get()getAll() 方法獲取)。

然後,程式碼使用 CookieStore.get() 獲取 "cookie1" 並記錄其屬性,然後使用 CookieStore.getAll()(不帶引數)獲取當前上下文中的所有 cookie。

js
async function cookieTest() {
  // Set a cookie passing name and value
  try {
    await cookieStore.set("cookie1", "cookie1-value");
  } catch (error) {
    console.log(`Error setting cookie1: ${error}`);
  }

  // Set a cookie passing an options object
  const day = 24 * 60 * 60 * 1000;
  try {
    await cookieStore.set({
      name: "cookie2",
      value: `cookie2-value`,
      expires: Date.now() + day,
      partitioned: true,
    });
  } catch (error) {
    console.log(`Error setting cookie2: ${error}`);
  }

  // Set cookie using document.cookie
  // (to demonstrate these are are fetched too)
  document.cookie = "favorite_food=tripe; SameSite=None; Secure";

  // Get named cookie and log properties
  const cookie1 = await cookieStore.get("cookie1");
  console.log(cookie1);

  // Get all cookies and log each
  const cookies = await cookieStore.getAll();
  if (cookies.length > 0) {
    console.log(`getAll(): ${cookies.length}:`);
    cookies.forEach((cookie) => console.log(cookie));
  } else {
    console.log("Cookies not found");
  }
}

cookieTest();

示例應分別記錄 "cookie1" 和所有三個 cookie。需要注意的是,使用 Document.cookie 建立的 cookie 的路徑可能與使用 set()(預設值為 /)建立的 cookie 不同。

本示例展示瞭如何使用 delete() 方法刪除命名 cookie。

程式碼首先設定兩個 cookie 並將它們記錄到控制檯。然後,我們刪除其中一個 cookie,然後再次列出所有 cookie。已刪除的 cookie ("cookie1") 出現在第一個日誌陣列中,而未出現在第二個陣列中。

js
async function cookieTest() {
  // Set two cookies
  try {
    await cookieStore.set("cookie1", "cookie1-value");
  } catch (error) {
    console.log(`Error setting cookie1: ${error}`);
  }

  try {
    await cookieStore.set("cookie2", "cookie2-value");
  } catch (error) {
    console.log(`Error setting cookie2: ${error}`);
  }

  // Log cookie names
  let cookieNames = (await cookieStore.getAll())
    .map((cookie) => cookie.name)
    .join(" ");
  console.log(`Initial cookies: ${cookieNames}`);

  // Delete cookie1
  await cookieStore.delete("cookie1");

  // Log cookies again (to show cookie1 deleted)
  cookieNames = (await cookieStore.getAll())
    .map((cookie) => cookie.name)
    .join(" ");
  console.log(
    `Cookies remaining after attempted deletions (cookie1 should be deleted): ${cookieNames}`,
  );
}

cookieTest();

規範

規範
Cookie Store API
# CookieStore

瀏覽器相容性