用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 @ 2024-11-29 13:25  王铁柱6  阅读(43)  评论(0)    收藏  举报