Appearance
Cookie 值获取 (getCookie)
获取指定名称的 Cookie 值。
签名
typescript
function getCookie(name: string): string;参数
name(string): Cookie 名称
返回值
(string) 返回获取到的 Cookie 值
- 成功获取返回对应的值
- 获取失败返回空字符串
''
示例
typescript
import { getCookie } from '@fu/matrix';
// 或
const getCookie = window.fuMatrix.getCookie;
// 获取名为 'userId' 的 cookie
document.cookie = 'userId=12345';
getCookie('userId'); // => "12345"
// 获取不存在的 cookie
getCookie('notExist'); // => ""
// SSR环境下
getCookie('any'); // => ""工作原理
- 检查是否为 SSR 环境,如果是则返回空字符串
- 获取 document.cookie 字符串
- 按分号分割所有 cookie
- 遍历查找指定名称的 cookie
- 找到后返回解码后的值,未找到返回空字符串
注意事项
- 在 SSR 环境下(无 document 对象)返回空字符串
- Cookie 名称区分大小写
- 返回的值会经过
decodeURIComponent解码 - 所有错误都会被捕获并返回空字符串,同时在控制台打印警告
- 支持处理带特殊字符的 Cookie 值
应用场景
- 获取用户身份标识
- 读取用户偏好设置
- 获取会话信息
- 读取追踪标识
相关函数
- getUserId - 获取用户ID(内部使用 getCookie)