← 中文资源

简体中文版本

document.cookie 读写 Cookie

赋值 name=value 加上 max-age 与 path 即可写入,整罐 cookie 以分号拼接回读:encodeURIComponent 编码值,max-age=0 的过期对在读取时直接消失。

阅读英文原文

实现说明

活动部件是函数 readCookie、writeCookie。 在这里做循环的是 for (const pair of document.cookie.split('; '))。

使用要点

  • 这是浏览器侧代码——document 在 Node 里解析不到。
  • 每一步打印都带着自己的标签:currency:、theme:、expired:。

常见问题

「document.cookie 读写 Cookie」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

主签名形如 function readCookie(name)

核心语句

return decodeURIComponent(pair.slice(prefix.length));

代码示例

// document.cookie exposes the cookie jar as one flat string; writes
// merge into existing pairs and expired pairs disappear on read
document.cookie = 'theme=dark; max-age=3600; path=/';
document.cookie = 'locale=zh-CN; max-age=31536000; path=/; samesite=lax';
document.cookie = 'flash=1; max-age=0'; // already expired, never appears

// Read one cookie: split the jar into pairs and match the name prefix
function readCookie(name) {
  const prefix = `${encodeURIComponent(name)}=`;
  for (const pair of document.cookie.split('; ')) {
    if (pair.startsWith(prefix)) {
      return decodeURIComponent(pair.slice(prefix.length));
    }
  }
  return null;
}

// Write one cookie: encode the value, then attach the attributes
function writeCookie(name, value, maxAgeSeconds) {
  document.cookie =
    `${encodeURIComponent(name)}=${encodeURIComponent(value)}; ` +
    `max-age=${maxAgeSeconds}; path=/; samesite=lax`;
}

writeCookie('currency', 'EUR;GBP', 86400); // semicolons survive encoding
console.log('currency:', readCookie('currency'));
console.log('theme:', readCookie('theme'));
console.log('expired:', readCookie('flash'));
console.log('jar contains locale:', document.cookie.includes('locale='));