@dhlx/cookie
TypeScript icon, indicating that this package has built-in type declarations

0.0.1 • Public • Published

@dhlx/cookie

npm License: MIT

轻量级浏览器 Cookie 操作工具库,提供类型安全的 Cookie 设置、获取和删除功能。

安装

npm install @dhlx/cookie
#
yarn add @dhlx/cookie

使用方法

设置 Cookie

import { setCookie } from '@dhlx/cookie';

// 简单设置
setCookie('username', 'john_doe');

// 带选项设置
setCookie('session', 'abc123xyz', {
  maxAge: 3600, // 1小时后过期
  path: '/dashboard',
  secure: true,
  sameSite: 'Lax'
});

// 设置特定过期时间
const expiryDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7天后
setCookie('preferences', 'dark_mode=true', {
  expires: expiryDate,
  domain: '.example.com'
});

获取 Cookie

import { getCookie } from '@dhlx/cookie';

const username = getCookie('username');
console.log(username); // 输出: "john_doe"

const nonExistent = getCookie('non_existent_cookie');
console.log(nonExistent); // 输出: undefined

删除 Cookie

import { deleteCookie } from '@dhlx/cookie';

// 简单删除
deleteCookie('username');

// 删除特定路径/域名的 Cookie
deleteCookie('session', '/dashboard', '.example.com');

API 文档

setCookie(name: string, value: string, options?: CookieOptions): void

设置一个 Cookie。

参数:

  • name: Cookie 名称
  • value: Cookie 值
  • options (可选): 配置对象
    interface CookieOptions {
      /** 过期时间(秒),优先级高于 expires */
      maxAge?: number;
      /** 过期日期对象 */
      expires?: Date;
      /** 生效路径 */
      path?: string;
      /** 生效域名 */
      domain?: string;
      /** 仅 HTTPS 传输 */
      secure?: boolean;
      /** SameSite 属性 */
      sameSite?: 'Strict' | 'Lax' | 'None';
    }

getCookie(name: string): string | undefined

获取指定 Cookie 的值。

参数:

  • name: 要获取的 Cookie 名称

返回值:
对应的值(未找到时返回 undefined

deleteCookie(name: string, path?: string, domain?: string): void

删除指定 Cookie。

参数:

  • name: 要删除的 Cookie 名称
  • path (可选): 原始设置时的路径
  • domain (可选): 原始设置时的域名

注意事项

  1. 删除 Cookie 要求
    删除 Cookie 时必须提供与设置时相同的 pathdomain 参数才能成功删除。如果设置时指定了这些选项,删除时也必须提供相同的值。

  2. 安全 Cookie
    如果设置时使用了 secure: true,删除时也必须使用 HTTPS 协议。

  3. SameSite 限制

    • SameSite=None 要求同时设置 Secure 属性
    • 不同浏览器的默认 SameSite 策略可能不同
  4. 值编码
    Cookie 名称和值会自动进行 URI 编码,确保特殊字符正确处理

Readme

Keywords

Package Sidebar

Install

npm i @dhlx/cookie

Weekly Downloads

4

Version

0.0.1

License

none

Unpacked Size

8.39 kB

Total Files

7

Last publish

Collaborators

  • lidenghui~