能用,Chrome 94+ 默认启用CookieStore API,但仅限HTTPS或localhost环境,HTTP页面静默失败且navigator.cookieStore为undefined;Firefox和Safari不支持。

CookieStore API 在 Chrome 中能用吗
不能直接用——CookieStore 是实验性 API,目前仅在 Chromium 94+(含 Chrome、Edge、Opera)中默认启用,且必须运行在 https 或 localhost 环境下。HTTP 页面会静默失败,navigator.cookieStore 为 undefined。
检查方式很简单:
if ('cookieStore' in navigator) {
console.log('支持 CookieStore');
} else {
console.log('不支持,回退到 document.cookie');
}- Firefox 和 Safari 完全不支持,别指望跨浏览器兼容
- Service Worker 中可用,但主页面 JS 同样可调用(无需进 SW)
- 不支持
HttpOnlycookie,这类 cookie 对 JS 完全不可见
如何用 cookieStore.get() 读取单个 Cookie
cookieStore.get() 返回 Promise,不是同步获取。它比 document.cookie 解析更可靠,尤其对含特殊字符(如空格、分号)的值。
常见错误是传错参数类型:
立即学习“前端免费学习笔记(深入)”;
- 传字符串:按 name 查找,但只返回第一个匹配项(即使同名多 domain/path)
- 传对象:可指定
domain、path、sameSite等过滤条件 - 不加
await直接用返回值?会得到 pending Promise,不是 cookie 对象
示例:
const cookie = await navigator.cookieStore.get('theme');
console.log(cookie?.value); // "dark"注意:cookie 可能为 undefined(未找到),务必判空。
cookieStore.set() 写入时要注意哪些字段
cookieStore.set() 接收一个对象或 CookieStoreSetOptions,关键字段和 document.cookie 字符串写法逻辑一致,但更结构化:
-
name和value必填;value会自动 URL 编码,不用手动encodeURIComponent -
expires接收Date实例(不是毫秒时间戳),设为过去时间可删除 -
domain必须是当前页面域名的上级域(如页面在app.example.com,可设为.example.com),否则写入失败且无提示 -
path默认为'/';若设为'/admin',则仅/admin及其子路径可读 -
secure: true强制要求 HTTPS;sameSite: 'Lax'或'Strict',不支持'None'除非同时设secure: true
安全写法示例:
await navigator.cookieStore.set({
name: 'token',
value: 'abc123',
expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
domain: '.example.com',
path: '/',
secure: true,
sameSite: 'Lax'
});批量读写用 keys() 和 getAll() 为什么容易出错
cookieStore.getAll() 返回所有可见 cookie 的数组,但它不会按 domain/path 自动去重,同一 name 可能出现多次(不同 scope)。而 cookieStore.keys() 并不存在——这是常见误解,API 没有 keys() 方法。
真正可用的批量操作只有:
-
getAll({ name: 'session' }):按 name 过滤 -
getAll({ domain: '.example.com' }):按 domain 过滤(需权限匹配) - 无法“列出所有 cookie 名称”,也不能原子性地清空全部(得逐个 set 过期)
性能上,getAll() 在 cookie 较多时可能变慢,且返回结果不保证顺序;如果只是判断某个 cookie 是否存在,用 get() 更轻量。
异步操作没有事务机制,set 多个 cookie 时无法保证全部成功或全部失败——每个 set() 是独立 Promise,需自行 Promise.allSettled() 处理。


















