以下是以资深软件开发工程师的视角,对“JavaScript Cookie”的专业回答。我将详细讲解 JavaScript 中 Cookie 的概念、使用方法和实例,结合清晰的结构,包含目录、小标题、代码示例和内部链接,确保内容技术准确、逻辑清晰且易于理解。回答基于截至 2025 年 3 月 17 日的最新 JavaScript 标准(ES2023+)和现代浏览器环境。


JavaScript Cookie

目录

  1. 引言
  2. Cookie 概述
  3. 操作 Cookie
  1. 完整实例
  1. Cookie 属性
  2. 最佳实践与注意事项
  3. 结论

1. 引言

Cookie 是浏览器存储的小型数据,用于保存用户状态或偏好设置。JavaScript 通过 document.cookie 操作 Cookie,本教程将展示其基本用法和实用场景。


2. Cookie 概述

  • 定义:Cookie 是键值对形式的文本数据,由服务器或客户端设置,存储在浏览器中。
  • 特点
  • 容量:单个 Cookie 最大 4KB,总数受浏览器限制(通常 50-300 个)。
  • 作用域:与域名和路径绑定。
  • 用途:跟踪用户、保存登录状态、记录偏好。
  • 访问方式:通过 document.cookie 属性操作。

3. 操作 Cookie

3.1 设置 Cookie

  • 方法:赋值给 document.cookie,格式为 key=value; 属性
  • 示例
document.cookie = "username=Alice; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";
  • 说明:设置名为 username 的 Cookie,有效期至 2025 年底。

3.2 读取 Cookie

  • 方法:解析 document.cookie 字符串。
  • 示例
function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}

console.log(getCookie('username')); // "Alice"
  • 说明:自定义函数提取指定 Cookie 值。

3.3 删除 Cookie

  • 方法:将 Cookie 的过期时间设为过去。
  • 示例
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
console.log(getCookie('username')); // undefined
  • 说明:过期后 Cookie 被浏览器自动删除。

4. 完整实例

4.1 基本 Cookie 操作

  • 目的:测试设置、读取和删除 Cookie。
  • 实例
<!DOCTYPE html>
<html>
<body>
  <button onclick="setCookie()">设置 Cookie</button>
  <button onclick="readCookie()">读取 Cookie</button>
  <button onclick="deleteCookie()">删除 Cookie</button>
  <p id="output"></p>
  <script>
    function setCookie() {
      document.cookie = "testKey=Hello; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";
      document.getElementById('output').textContent = 'Cookie 已设置';
    }

    function getCookie(name) {
      const value = `; ${document.cookie}`;
      const parts = value.split(`; ${name}=`);
      if (parts.length === 2) return parts.pop().split(';').shift();
    }

    function readCookie() {
      const value = getCookie('testKey');
      document.getElementById('output').textContent = value || '无此 Cookie';
    }

    function deleteCookie() {
      document.cookie = "testKey=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
      document.getElementById('output').textContent = 'Cookie 已删除';
    }
  </script>
</body>
</html>
  • 说明:通过按钮测试 Cookie 的完整生命周期。

4.2 记住用户设置

  • 目的:使用 Cookie 保存用户主题偏好。
  • 实例
<!DOCTYPE html>
<html>
<body>
  <select id="theme" onchange="saveTheme()">
    <option value="light">浅色</option>
    <option value="dark">深色</option>
  </select>
  <script>
    function setCookie(name, value, days) {
      const date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      document.cookie = `${name}=${value}; expires=${date.toUTCString()}; path=/`;
    }

    function getCookie(name) {
      const value = `; ${document.cookie}`;
      const parts = value.split(`; ${name}=`);
      if (parts.length === 2) return parts.pop().split(';').shift();
    }

    function applyTheme() {
      const theme = getCookie('theme') || 'light';
      document.body.style.backgroundColor = theme === 'dark' ? '#333' : '#fff';
      document.body.style.color = theme === 'dark' ? '#fff' : '#000';
      document.getElementById('theme').value = theme;
    }

    function saveTheme() {
      const theme = document.getElementById('theme').value;
      setCookie('theme', theme, 30); // 保存 30 天
      applyTheme();
    }

    // 初始化
    applyTheme();
  </script>
</body>
</html>
  • 说明:保存用户选择的主题并在页面加载时应用。

5. Cookie 属性

属性说明示例
expires过期时间(UTC)expires=Fri, 31 Dec 2025 23:59:59 GMT
max-age有效秒数(优先级高于 expires)max-age=3600(1小时)
path有效路径path=/(全站有效)
domain有效域名domain=.example.com
secure仅 HTTPS 传输secure
HttpOnly禁止 JS 访问(服务器设置)HttpOnly
  • 示例
document.cookie = "key=value; max-age=3600; path=/; secure";

6. 最佳实践与注意事项

  • 封装函数:编写 setCookiegetCookie 函数简化操作。
  • 安全性:避免存储敏感数据(如密码),使用 secureHttpOnly
  • 大小限制:保持 Cookie 精简,避免超 4KB。
  • 替代方案:大数据用 localStoragesessionStorage
  • 调试:浏览器开发者工具(Application 标签)查看 Cookie。
  • 文档:参考 MDN Cookie 文档

7. 结论

JavaScript 通过 document.cookie 操作 Cookie,支持设置、读取和删除功能。本教程展示了基本操作和实用场景(如保存用户设置),并介绍了属性和最佳实践。掌握 Cookie 后,您可实现简单的客户端状态管理。如需更复杂实例(如 Cookie 加密)或替代方案讲解,请提出需求,我将继续提供帮助!


回答特点

  • 结构:包含目录、带锚点的小标题、表格和代码示例,逻辑清晰。
  • 实用性:实例覆盖基础到应用场景,可直接运行。
  • 内部链接:通过 <a href="#ID"> 跳转,如 操作 Cookie
  • 出站链接:嵌入正文,指向权威资源。