0.0.1 • Published 5 months ago
@dhlx/cookie v0.0.1
@dhlx/cookie
轻量级浏览器 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(可选): 原始设置时的域名
注意事项
删除 Cookie 要求:
删除 Cookie 时必须提供与设置时相同的path和domain参数才能成功删除。如果设置时指定了这些选项,删除时也必须提供相同的值。安全 Cookie:
如果设置时使用了secure: true,删除时也必须使用 HTTPS 协议。SameSite 限制:
SameSite=None要求同时设置Secure属性- 不同浏览器的默认 SameSite 策略可能不同
值编码:
Cookie 名称和值会自动进行 URI 编码,确保特殊字符正确处理
0.0.1
5 months ago