轻量级浏览器 Cookie 操作工具库,提供类型安全的 Cookie 设置、获取和删除功能。
npm install @dhlx/cookie
# 或
yarn add @dhlx/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'
});
import { getCookie } from '@dhlx/cookie';
const username = getCookie('username');
console.log(username); // 输出: "john_doe"
const nonExistent = getCookie('non_existent_cookie');
console.log(nonExistent); // 输出: undefined
import { deleteCookie } from '@dhlx/cookie';
// 简单删除
deleteCookie('username');
// 删除特定路径/域名的 Cookie
deleteCookie('session', '/dashboard', '.example.com');
设置一个 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'; }
获取指定 Cookie 的值。
参数:
-
name
: 要获取的 Cookie 名称
返回值:
对应的值(未找到时返回 undefined
)
删除指定 Cookie。
参数:
-
name
: 要删除的 Cookie 名称 -
path
(可选): 原始设置时的路径 -
domain
(可选): 原始设置时的域名
-
删除 Cookie 要求:
删除 Cookie 时必须提供与设置时相同的path
和domain
参数才能成功删除。如果设置时指定了这些选项,删除时也必须提供相同的值。 -
安全 Cookie:
如果设置时使用了secure: true
,删除时也必须使用 HTTPS 协议。 -
SameSite 限制:
-
SameSite=None
要求同时设置Secure
属性 - 不同浏览器的默认 SameSite 策略可能不同
-
-
值编码:
Cookie 名称和值会自动进行 URI 编码,确保特殊字符正确处理