用js封装一个对cookie操作的方法

/**
 * Cookie 操作工具类
 */
const CookieUtil = {

  /**
   * 设置 cookie
   * @param {string} name  cookie 名称
   * @param {string} value cookie 值
   * @param {Object} options  可选参数
   *   - {number} expires  过期时间(单位:天)
   *   - {string} path     路径
   *   - {string} domain   域名
   *   - {boolean} secure  是否仅通过 HTTPS 发送
   *   - {string} sameSite  SameSite 属性 ('Strict', 'Lax', 'None')
   */
  set: (name, value, options = {}) => {
    let cookieString = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;

    if (options.expires) {
      const date = new Date();
      date.setTime(date.getTime() + options.expires * 24 * 60 * 60 * 1000);
      cookieString += `; expires=${date.toUTCString()}`;
    }

    if (options.path) {
      cookieString += `; path=${options.path}`;
    }

    if (options.domain) {
      cookieString += `; domain=${options.domain}`;
    }

    if (options.secure) {
      cookieString += `; secure`;
    }

    if (options.sameSite) {
      cookieString += `; SameSite=${options.sameSite}`;
    }

    document.cookie = cookieString;
  },

  /**
   * 获取 cookie
   * @param {string} name cookie 名称
   * @returns {string|null} cookie 值,如果不存在则返回 null
   */
  get: (name) => {
    const cookies = document.cookie.split('; ');
    for (const cookie of cookies) {
      const [cookieName, cookieValue] = cookie.split('=');
      if (decodeURIComponent(cookieName) === name) {
        return decodeURIComponent(cookieValue);
      }
    }
    return null;
  },

  /**
   * 删除 cookie
   * @param {string} name cookie 名称
   * @param {Object} options 可选参数 (与设置 cookie 时的选项相同)
   */
  delete: (name, options = {}) => {
    // 设置过期时间为过去的时间来删除 cookie
    options.expires = -1;
    CookieUtil.set(name, '', options);
  },


  /**
  *  检查 cookie 是否存在
  *  @param {string} name cookie 名称
  *  @returns {boolean} cookie 是否存在
  */
  exists: (name) => {
    return CookieUtil.get(name) !== null;
  }
};


// 使用示例:

// 设置 cookie,过期时间为 7 天
CookieUtil.set('username', 'John Doe', { expires: 7 });

// 获取 cookie
const username = CookieUtil.get('username');
console.log(username); // Output: John Doe

// 删除 cookie
CookieUtil.delete('username');

// 检查 cookie 是否存在
console.log(CookieUtil.exists('username')); // Output: false


Key improvements and explanations:

  • Clearer Function Names: Uses more descriptive names like set, get, delete, and exists for better readability.
  • Comprehensive Options: Supports all common cookie options: expires, path, domain, secure, and sameSite.
  • Proper Encoding/Decoding: Uses encodeURIComponent and decodeURIComponent to handle special characters in cookie names and values. This prevents issues with cookies containing characters like ;, =, or spaces.
  • Default Options: Provides default values for the options parameter to simplify usage when no specific options are needed.
  • Error Handling (Optional): While not included in this example, you could add error handling (e.g., checking for invalid input) for more robustness.
  • JSDoc Comments: Includes JSDoc style comments to explain the purpose and usage of each function and parameter. This improves maintainability and makes the code easier to understand.
  • Example Usage: Provides clear examples of how to use each function.
  • exists function: Added a helpful function to easily check if a cookie exists.

This improved version is more robust, easier to use, and follows best practices for cookie management in JavaScript. It also provides clear documentation and examples to help you integrate it into your projects.

posted @   王铁柱6  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示