Cookie Store API

安全上下文: 此项功能仅在一些支持的浏览器安全上下文(HTTPS)中可用。

备注: 此特性在 Service Worker 中可用。

Cookie Store API 是一个用于管理 cookies 的异步 API,可在 window 和 Service Worker 中使用。

概念和用法

现存的获取和设置的 cookies 的方法包括将 document.cookie 作为键/值对字符串使用。除了麻烦且容易出错之外,在现代网络开发的背景下它也存在许多问题。

document.cookie 接口是同步、单线程和阻塞的。编写 cookie 时,你必须等待浏览器更新包含所有 cookies 的字符串。此外,依赖 document 意味着访问不到 document 对象的 Service Worker 无法访问 cookie。

Cookie Store API 提供了管理 Cookie 更新的方法。方法是异步和基于 Promise 的,因此不会阻塞事件循环。方法不依赖于 document,所以对于 Service Worker 也有效。获取和设置 cookie 的方法还通过错误消息提供了更多反馈。这意味着 Web 开发人员不必设置后,立即读取 cookie 来检查是否成功设置。

接口

CookieStore 实验性

CookieStore 接口允许获取和设置 cookies。

CookieStoreManager 实验性

CookieStoreManager 接口提供了 Service Worker Registration 用于允许 Service Worker 订阅 cookie 变更事件。

CookieChangeEvent 实验性

Window 上下文中发生任何脚本可见的 cookie 更改时,CookieStore 对象会派发出名为 changeCookieChangeEvent 事件。

ExtendableCookieChangeEvent

ServiceWorkerGlobalScope 上下文中发生任何脚本可见的 cookie 更改时,ExtendableCookieChangeEvent 将被派发,事件名为 cookiechange

对其他接口的扩展

ServiceWorkerGlobalScope.cookieStore 只读 实验性

返回此 Service Worker 关联的 CookieStore 对象的引用。

ServiceWorkerRegistration.cookies 只读 实验性

返回 CookieStoreManager 接口的引用,它允许 Web APP 订阅和取消订阅 cookie 变更事件。

Window.cookieStore 只读 实验性

返回当前 document 上下文的 CookieStore 对象。

cookiechange 事件 实验性

当 cookie 发生任何更改时触发,与 Service Worker 的 Cookie 更改订阅列表相匹配。

规范

Specification
Cookie Store API

浏览器兼容性

api.CookieStore

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
CookieStore
change event
delete
partitioned option
get
domain in return value
expires in return value
name in return value
partitioned in return value
Experimental
path in return value
sameSite in return value
secure in return value
value in return value
getAll
domain in return value
expires in return value
name in return value
partitioned in return value
Experimental
path in return value
sameSite in return value
secure in return value
value in return value
set
partitioned option

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
In development. Supported in a pre-release version.
In development. Supported in a pre-release version.
No support
No support
Experimental. Expect behavior to change in the future.
See implementation notes.

api.CookieStoreManager

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
CookieStoreManager
getSubscriptions
subscribe
unsubscribe

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support

参见