HTML DOM Cookie 操作详解 如何在网页中读取写入和删除Cookie并解决常见安全与兼容性问题

什么是Cookie及其工作原理
Cookie是服务器发送到用户浏览器并保存在本地的一小块数据。它会在浏览器向同一服务器再次发起请求时被携带并发送到服务器端。Cookie通常用于身份验证、购物车、个性化设置等场景。
Cookie的基本结构
每个Cookie都是一个键值对,例如:
username=JohnDoe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/; Secure; HttpOnly
Cookie的属性说明
name=value
(必需):Cookie的名称和值
expires
:Cookie的过期时间(GMT格式)
max-age
:Cookie的有效期(秒)
domain
:Cookie生效的域名
path
:Cookie生效的路径
Secure
:仅通过HTTPS传输
HttpOnly
:禁止JavaScript访问(增强安全性)
SameSite
:防止CSRF攻击(Strict/Lax/None)
JavaScript操作Cookie的方法
1. 读取Cookie
// 获取所有Cookie
function getAllCookies() {
const cookies = document.cookie;
if (!cookies) return {};

const cookieList = {};
cookies.split(‘;’).forEach(cookie => {
const [name, value] = cookie.trim().split(‘=’);
cookieList[name] = decodeURIComponent(value);
});

return cookieList;
}

// 获取特定Cookie
function getCookie(name) {
const cookies = document.cookie.split(‘;’);
for (let cookie of cookies) {
const [cookieName, cookieValue] = cookie.trim().split(‘=’);
if (cookieName === name) {
return decodeURIComponent(cookieValue);
}
}
return null;
}

// 使用示例
console.log(getAllCookies());
console.log(getCookie(‘username’));
2. 写入/设置Cookie
/**
* 设置Cookie
* @param {string} name – Cookie名称
* @param {string} value – Cookie值
* @param {object} options – 配置选项
* @param {number} options.expires – 过期时间(天数)
* @param {string} options.path – 路径
* @param {string} options.domain – 域名
* @param {boolean} options.secure – 安全标志
* @param {boolean} options.httpOnly – HttpOnly标志
* @param {string} options.sameSite – SameSite策略
*/
function setCookie(name, value, options = {}) {
// 基础Cookie字符串
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()}`;
}

// 处理max-age(优先级高于expires)
if (options.maxAge) {
cookieString += `; max-age=${options.maxAge}`;
}

// 处理路径
if (options.path) {
cookieString += `; path=${options.path}`;
} else {
cookieString += `; path=/`; // 默认路径
}

// 处理域名
if (options.domain) {
cookieString += `; domain=${options.domain}`;
}

// 处理Secure标志
if (options.secure) {
cookieString += `; Secure`;
}

// 处理HttpOnly标志(注意:在浏览器JavaScript中设置HttpOnly会无效)
if (options.httpOnly) {
// 在浏览器JS中无法设置HttpOnly,这是服务器端的特性
console.warn(‘HttpOnly标志只能在服务器端设置,浏览器JavaScript设置将被忽略’);
}

// 处理SameSite策略
if (options.sameSite) {
cookieString += `; SameSite=${options.sameSite}`;
}

// 设置Cookie
document.cookie = cookieString;
return cookieString;
}

// 使用示例
// 基础设置
setCookie(‘username’, ‘JohnDoe’);

// 完整设置
setCookie(‘session_id’, ‘abc123xyz’, {
expires: 7,
path: ‘/’,
domain: ‘example.com’,
secure: true,
sameSite: ‘Lax’
});

// 设置临时Cookie(会话Cookie)
setCookie(‘temp_data’, ‘temporary’, {
path: ‘/app’,
sameSite: ‘Strict’
});
3. 删除Cookie
/**
* 删除Cookie
* @param {string} name – 要删除的Cookie名称
* @param {object} options – 配置选项(需与设置时一致)
*/
function deleteCookie(name, options = {}) {
// 删除Cookie的原理是将过期时间设置为过去的时间
const defaultOptions = {
expires: -1,
path: ‘/’,
domain: options.domain || undefined
};

// 合并选项
const deleteOptions = { …defaultOptions, …options };

// 设置过期时间为过去
setCookie(name, ”, deleteOptions);
}

// 使用示例
deleteCookie(‘username’);
deleteCookie(‘session_id’, { path: ‘/’, domain: ‘example.com’ });

// 替代方法(直接设置过期时间)
function deleteCookieAlternative(name, path = ‘/’, domain = null) {
let cookieString = `${encodeURIComponent(name)}=; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
cookieString += `; path=${path}`;
if (domain) {
cookieString += `; domain=${domain}`;
}
document.cookie = cookieString;
}
4. Cookie操作工具类
class CookieManager {
/**
* 获取所有Cookie
*/
static getAll() {
const cookies = {};
if (!document.cookie) return cookies;

document.cookie.split(‘;’).forEach(cookie => {
const [name, value] = cookie.trim().split(‘=’);
if (name) {
cookies[decodeURIComponent(name)] = decodeURIComponent(value);
}
});

return cookies;
}

/**
* 获取单个Cookie
*/
static get(name) {
const cookies = this.getAll();
return cookies[name] || null;
}

/**
* 设置Cookie
*/
static 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.maxAge) {
cookieString += `; max-age=${options.maxAge}`;
}

if (options.path) {
cookieString += `; path=${options.path}`;
} else {
cookieString += `; path=/`;
}

if (1) {
cookieString += `; domain=${options.domain}`;
}

if (options.secure) {
cookieString += `; Secure`;
}

if (options.sameSite) {
cookieString += `; SameSite=${options.sameSite}`;
}

document.cookie = cookieString;
return true;
}

/**
* 删除Cookie
*/
static remove(name, options = {}) {
const deleteOptions = {
expires: -1,
path: options.path || ‘/’,
domain: options.domain || undefined
};
return this.set(name, ”, deleteOptions);
}

/**
* 检查Cookie是否存在
*/
static exists(name) {
return this.get(name) !== null;
}

/**
* 清空所有Cookie(谨慎使用)
*/
static clear() {
const cookies = this.getAll();
Object.keys(cookies).forEach(name => {
this.remove(name);
});
}
}

// 使用示例
CookieManager.set(‘user_pref’, ‘dark_mode’, { expires: 30 });
const pref = CookieManager.get(‘user_pref’);
CookieManager.remove(‘user_pref’);
安全最佳实践
1. HttpOnly标志
HttpOnly标志可以防止JavaScript访问Cookie,有效防范XSS攻击窃取Cookie。
注意
:浏览器JavaScript无法设置HttpOnly标志,这只能在服务器端设置。
// 服务器端设置示例(Node.js/Express)
app.get(‘/set-secure-cookie’, (req, res) => {
res.cookie(‘session_id’, ‘abc123’, {
httpOnly: true, // 防止JS访问
secure: true, // 仅HTTPS
sameSite: ‘strict’, // 防止CSRF
maxAge: 24 * 60 * 60 * 1000 // 24小时
});
res.send(‘Cookie已设置’);
});
2. Secure标志
Secure标志确保Cookie仅通过HTTPS传输,防止中间人攻击。
// 在HTTPS环境下设置Secure Cookie
if (location.protocol === ‘https:’) {
setCookie(‘secure_data’, ‘sensitive’, {
secure: true,
expires: 1
});
}
3. SameSite属性
SameSite属性可以防止CSRF攻击,有三个值:
Strict
:严格模式,完全禁止第三方Cookie
Lax
:宽松模式,允许顶级导航时发送Cookie
None
:允许所有跨站请求(必须配合Secure)
// 设置SameSite
setCookie(‘csrf_token’, ‘token123’, {
sameSite: ‘Strict’,
secure: true,
httpOnly: true
});
4. Cookie大小限制
每个Cookie最大4KB,每个域名下最多20-50个Cookie(浏览器不同)。
// 检查Cookie大小
function getCookieSize(name, value) {
return (name + ‘=’ + value).length;
}

// 避免存储大量数据
function safeSetCookie(name, value, options = {}) {
const size = getCookieSize(name, value);
if (size > 4000) {
console.warn(`Cookie大小为${size}字节,超过4KB限制`);
return false;
}
return setCookie(name, value, options);
}
5. 避免存储敏感信息
错误示例
:
// 永远不要这样做!
setCookie(‘password’, ‘secret123’);
setCookie(‘credit_card’, ‘1234-5678-9012-3456’);
正确做法
:
// 只存储会话标识符
setCookie(‘session_id’, ‘random_token’, {
httpOnly: true,
secure: true,
sameSite: ‘Strict’
});
// 敏感数据存储在服务器端
兼容性问题及解决方案
1. 旧版浏览器兼容性
问题:IE6-7不支持
encodeURIComponent
// 兼容旧版浏览器的编码函数
function encodeCookieValue(value) {
// 检查浏览器是否支持encodeURIComponent
if (typeof encodeURIComponent === ‘function’) {
return encodeURIComponent(value);
}
// 旧版浏览器手动编码
return value.replace(/[^a-zA-Z0-9]/g, function(c) {
return ‘%’ + c.charCodeAt(0).toString(16).toUpperCase();
});
}

function decodeCookieValue(value) {
if (typeof decodeURIComponent === ‘function’) {
return decodeURIComponent(value);
}
// 旧版浏览器手动解码
return value.replace(/%[0-9A-Fa-f]{2}/g, function(match) {
return String.fromCharCode(parseInt(match.substr(1), 16));
});
}
问题:IE6-8不支持
JSON.stringify
// 兼容JSON序列化
function serializeValue(value) {
if (typeof JSON !== ‘undefined’ && JSON.stringify) {
return JSON.stringify(value);
}
// 手动序列化简单对象
if (typeof value === ‘object’ && value !== null) {
const parts = [];
for (const key in value) {
if (value.hasOwnProperty(key)) {
parts.push(`${key}:${value[key]}`);
}
}
return `{${parts.join(‘,’)}}`;
}
return String(value);
}

function deserializeValue(value) {
if (typeof JSON !== ‘undefined’ && JSON.parse) {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
}
// 手动反序列化
if (value.startsWith(‘{‘) && value.endsWith(‘}’)) {
const obj = {};
const content = value.slice(1, -1);
const pairs = content.split(‘,’);
pairs.forEach(pair => {
const [key, val] = pair.split(‘:’);
obj[key] = val;
});
return obj;
}
return value;
}
2. 跨域Cookie问题
问题:子域名共享Cookie
// 设置共享Cookie到父域名
function setSharedCookie(name, value, options = {}) {
// 获取当前域名的父域名
const domain = location.hostname.split(‘.’).slice(-2).join(‘.’);

// 只有在生产环境才设置domain
if (location.hostname !== ‘localhost’ && location.hostname !== ‘127.0.0.1’) {
options.domain = domain;
}

return setCookie(name, value, options);
}

// 使用示例
// 在app.example.com设置,example.com和www.example.com都能访问
setSharedCookie(‘shared_session’, ‘abc123’, { expires: 7 });
问题:跨域请求Cookie丢失
// 前端设置withCredentials
function makeCrossDomainRequest(url, data) {
const xhr = new XMLHttpRequest();
xhr.open(‘POST’, url, true);
xhr.withCredentials = true; // 允许发送跨域Cookie
xhr.setRequestHeader(‘Content-Type’, ‘application/json’);
xhr.send(JSON.stringify(data));

xhr.onload = function() {
if (xhr.status === 200) {
console.log(‘请求成功’);
}
};
}

// fetch API
fetch(url, {
method: ‘POST’,
credentials: ‘include’, // 包含Cookie
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify(data)
});
3. 私有浏览模式问题
问题:某些浏览器在私有模式下会阻止或限制Cookie
// 检测私有浏览模式(不完全可靠)
function isPrivateMode(callback) {
try {
// 尝试设置并立即读取
const testKey = ‘private_test’;
localStorage.setItem(testKey, ‘test’);
localStorage.removeItem(testiKey);
callback(false);
} catch (e) {
// 如果localStorage失败,可能是私有模式
callback(true);
}
}

// 降级处理
function safeCookieOperation(name, value, options) {
try {
setCookie(name, value, options);
return true;
} catch (e) {
console.warn(‘Cookie操作失败,可能处于私有模式’, e);
// 降级方案:使用sessionStorage或内存存储
try {
sessionStorage.setItem(`cookie_fallback_${name}`, value);
return true;
} catch (e2) {
// 最终降级:内存存储
window.cookieFallbackStore = window.cookieFallbackStore || {};
window.cookieFallbackStore[name] = value;
return true;
}
}
}
4. 跨浏览器Cookie同步问题
问题:不同浏览器对Cookie属性的解析差异
// 浏览器特性检测
const browserFeatures = {
supportsSameSite: null,
supportsMaxAge: null,
supportsHttpOnly: null
};

function detectBrowserFeatures() {
// 检测SameSite支持
try {
document.cookie = ‘test_samesite=1; SameSite=Strict’;
browserFeatures.supportsSameSite = document.cookie.includes(‘test_samesite’);
document.cookie = ‘test_samesite=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/’;
} catch (e) {
browserFeatures.supportsSameSite = false;
}

// 检测max-age支持
try {
document.cookie = ‘test_maxage=1; max-age=1’;
browserFeatures.supportsMaxAge = document.cookie.includes(‘test_maxage’);
document.cookie = ‘test_maxage=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/’;
} catch (e) {
browserFeatures.supportsMaxAge = false;
}

return browserFeatures;
}

// 自适应设置Cookie
function adaptiveSetCookie(name, value, options = {}) {
const features = detectBrowserFeatures();

// 如果不支持max-age,转换为expires
if (!features.supportsMaxAge && options.maxAge) {
options.expires = options.maxAge / (24 * 60 * 60); // 秒转天
delete options.maxAge;
}

// 如果不支持SameSite,移除该选项
if (!features.supportsSameSite) {
delete options.sameSite;
}

return setCookie(name, value, options);
}
5. 移动端浏览器特殊问题
问题:iOS Safari的第三方Cookie限制
// 检测iOS Safari
function isIOSSafari() {
return /iPad|iPhone|iPod/.test(navigator.userAgent) &&
/Safari/.test(nnavigator.userAgent) &&
!/Chrome/.test(navigator.userAgent);
}

// iOS Safari Cookie处理策略
function handleIOSSafariCookie(name, value, options = {}) {
if (isIOSSafari()) {
// iOS Safari 13+限制第三方Cookie
// 确保设置第一方Cookie
options.domain = location.hostname;
options.path = ‘/’;

// 避免使用SameSite=None(除非必要)
if (options.sameSite === ‘None’) {
console.warn(‘iOS Safari可能不支持SameSite=None’);
}

// 考虑使用localStorage作为补充
if (options.expires > 7) {
console.warn(‘iOS Safari可能清除长期Cookie’);
}
}

return setCookie(name, value, options);
}
实际应用场景示例
1. 用户偏好设置系统
class UserPreferences {
constructor() {
this.cookieName = ‘user_preferences’;
this.preferences = this.loadPreferences();
}

loadPreferences() {
const cookieValue = getCookie(this.cookieName);
if (cookieValue) {
try {
return JSON.parse(cookieValue);
} catch (e) {
return {};
}
}
return {};
}

savePreferences() {
const value = JSON.stringify(this.preferences);
setCookie(this.cookieName, value, {
expires: 365,
path: ‘/’,
sameSite: ‘Lax’
});
}

get(key) {
return this.preferences[key];
}

set(key, value) {
this.preferences[key] = value;
this.savePreferences();
}

remove(key) {
delete this.preferences[key];
this.savePreferences();
}

clear() {
this.preferences = {};
deleteCookie(this.cookieName, { path: ‘/’ });
}
}

// 使用示例
const prefs = new UserPreferences();
prefs.set(‘theme’, ‘dark’);
prefs.set(‘language’, ‘zh-CN’);
console.log(prefs.get(‘theme’)); // ‘dark’
2. 购物车实现
class ShoppingCart {
constructor() {
this.cookieName = ‘shopping_cart’;
this.items = this.loadCart();
}

loadCart() {
const cookieValue = getCookie(this.cookieName);
if (cookieValue) {
try {
const data = JSON.parse(cookieValue);
return Array.isArray(data) ? data : [];
} catch (e) {
return [];
}
}
return [];
}

saveCart() {
const value = JSON.stringify(this.items);
// 检查大小限制
if (value.length > 4000) {
console.warn(‘购物车数据过大,考虑使用服务器存储’);
return false;
}
setCookie(this.cookieName, value, {
expires: 7,
path: ‘/’,
sameSite: ‘Lax’
});
return true;
}

addItem(product) {
const existing = this.items.find(item => item.id === product.id);
if (existing) {
existing.quantity += product.quantity || 1;
} else {
this.items.push({
id: product.id,
name: product.name,
price: product.price,
quantity: product.quantity || 1
});
}
return this.saveCart();
}

removeItem(productId) {
this.items = this.items.filter(item => item.id !== productId);
return this.saveCart();
}

updateQuantity(productId, quantity) {
const item = this.items.find(item => item.id === productId);
if (item) {
item.quantity = quantity;
return this.saveCart();
}
return false;
}

clear() {
this.items = [];
deleteCookie(this.cookieName, { path: ‘/’ });
}

getTotal() {
return this.items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}

getCount() {
return this.items.reduce((sum, item) => sum + item.quantity, 0);
}
}

// 使用示例
const cart = new ShoppingCart();
cart.addItem({ id: 1, name: ‘商品A’, price: 100, quantity: 2 });
cart.addItem({ id: 2, name: ‘商品B’, price: 200 });
console.log(cart.getTotal()); // 400
console.log(cart.getCount()); // 3
3. 会话管理与自动登录
class SessionManager {
constructor() {
this.sessionCookieName = ‘session_id’;
this.userCookieName = ‘user_info’;
}

// 创建会话
createSession(userId, rememberMe = false) {
const sessionId = this.generateSessionId();
const expireDays = rememberMe ? 30 : 1; // 记住我:30天,否则1天

// 设置会话ID(HttpOnly,Secure)
this.setHttpOnlyCookie(this.sessionCookieName, sessionId, expireDays);

// 存储用户信息(非敏感)
setCookie(this.userCookieName, JSON.stringify({
userId: userId,
lastLogin: new Date().toISOString()
}), {
expires: expireDays,
path: ‘/’,
sameSite: ‘Lax’
});

return sessionId;
}

// 生成安全的会话ID
generateSessionId() {
const array = new Uint8Array(32);
window.crypto.getRandomValues(array);
return Array.from(array, byte => byte.toString(16).padStart(2, ‘0’)).join(”);
}

// 设置HttpOnly Cookie(需要服务器端)
setHttpOnlyCookie(name, value, days) {
// 注意:浏览器JS无法设置HttpOnly
// 这里只是模拟,实际需要服务器端设置
console.log(`服务器端应设置: ${name}=…; HttpOnly; Secure; Max-Age=${days * 86400}`);

// 作为降级方案,使用带Secure的普通Cookie
setCookie(name, value, {
expires: days,
path: ‘/’,
secure: true,
sameSite: ‘Strict’
});
}

// 验证会话
validateSession() {
const sessionId = getCookie(this.sessionCookieName);
const userInfo = getCookie(this.userCookieName);

if (!sessionId || !userInfo) {
return false;
}

try {
const user = JSON.parse(userInfo);
// 检查会话是否过期(简单检查)
const lastLogin = new Date(user.lastLogin);
const now = new Date();
const daysSinceLogin = (now – lastLogin) / (1000 * 60 * 60 * 24);

if (daysSinceLogin > 30) {
this.logout();
return false;
}

return user.userId;
} catch (e) {
return false;
}
}

// 登出
logout() {
deleteCookie(this.sessionCookieName, { path: ‘/’ });
deleteCookie(this.userCookieName, { path: ‘/’ });
}
}

// 使用示例
const session = new SessionManager();
// 用户登录后
session.createSession(‘user123’, true);
// 页面加载时验证
const userId = session.validateSession();
if (userId) {
console.log(‘用户已登录:’, userId);
} else {
console.log(‘需要登录’);
}
4. A/B测试与功能开关
class FeatureManager {
constructor() {
this.cookieName = ‘feature_flags’;
this.features = this.loadFeatures();
}

loadFeatures() {
const cookieValue = getCookie(this.cookieName);
if (cookieValue) {
try {
return JSON.parse(cookieValue);
} catch (e) {
return {};
}
}
return {};
}

saveFeatures() {
setCookie(this.cookieName, JSON.stringify(this.features), {
expires: 30,
path: ‘/’,
sameSite: ‘Lax’
});
}

// 获取用户分组
getABGroup(testName) {
if (!this.features[testName]) {
// 随机分配A/B组(50/50)
const group = Math.random() < 0.5 ? 'A' : 'B'; this.features[testName] = group; this.saveFeatures(); } return this.features[testName]; } // 检查功能是否启用 isFeatureEnabled(featureName) { return this.features[featureName] === true; } // 启用功能 enableFeature(featureName) { this.features[featureName] = true; this.saveFeatures(); } // 禁用功能 disableFeature(featureName) { this.features[featureName] = false; this.saveFeatures(); } // 清除所有功能标记 clearFeatures() { this.features = {}; deleteCookie(this.cookieName, { path: '/' }); } } // 使用示例 const featureManager = new FeatureManager(); // A/B测试 const group = featureManager.getABGroup('new_checkout_flow'); if (group === 'A') { // 显示新设计 showNewCheckout(); } else { // 显示旧设计 showOldCheckout(); } // 功能开关 if (featureManager.isFeatureEnabled('dark_mode')) { enableDarkMode(); } 调试与故障排除 1. Cookie调试工具 class CookieDebugger { // 显示所有Cookie信息 static debug() { const cookies = document.cookie.split(';'); console.log('=== Cookie Debug Info ==='); console.log(`Total Cookies: ${cookies.length}`); cookies.forEach((cookie, index) => {
const [name, value] = cookie.trim().split(‘=’);
console.log(`${index + 1}. ${name} = ${decodeURIComponent(value || ”)}`);
});

console.log(‘=========================’);
}

// 检查Cookie是否可读
static checkAccessibility(name) {
const value = getCookie(name);
if (value === null) {
console.log(`Cookie “${name}” 不可访问或不存在`);
return false;
}
console.log(`Cookie “${name}” 可访问,值: ${value}`);
return true;
}

// 检查Cookie大小
static checkSize(name) {
const value = getCookie(name);
if (value === null) return 0;
const size = (name + ‘=’ + value).length;
console.log(`Cookie “${name}” 大小: ${size} 字节`);
return size;
}

// 检查所有Cookie大小
static checkAllSizes() {
const cookies = document.cookie.split(‘;’);
let totalSize = 0;

console.log(‘=== Cookie Size Analysis ===’);
cookies.forEach(cookie => {
const [name, value] = cookie.trim().split(‘=’);
const size = (name + ‘=’ + (value || ”)).length;
totalSize += size;
console.log(`${name}: ${size} bytes`);
});

console.log(`Total: ${totalSize} bytes`);
console.log(`Remaining: ${4096 – totalSize} bytes`);
}

// 检查Cookie属性
static checkAttributes(name) {
// 尝试读取Cookie
const value = getCookie(name);
if (value === null) {
console.log(`Cookie “${name}” 不存在`);
return;
}

console.log(`Cookie “${name}” 属性:`);
console.log(` – Value: ${value}`);
console.log(` – Size: ${(name + ‘=’ + value).length} bytes`);

// 检查是否是HttpOnly(无法直接检测,只能通过行为推断)
console.log(‘ – HttpOnly: 无法通过JS检测(需服务器端确认)’);

// 检查Secure(检查当前协议)
if (location.protocol === ‘https:’) {
console.log(‘ – Secure: 当前是HTTPS环境’);
} else {
console.log(‘ – Secure: 当前是HTTP环境(不安全)’);
}
}
}

// 使用示例
CookieDebugger.debug();
CookieDebugger.checkAccessibility(‘session_id’);
CookieDebugger.checkAllSizes();
2. 常见问题排查
问题1:Cookie设置后立即消失
// 可能原因:路径不匹配
function fixPathIssue() {
// 确保设置path=’/’使其在全站可用
setCookie(‘test’, ‘value’, { path: ‘/’ });

// 或者获取当前路径
const currentPath = location.pathname;
setCookie(‘test’, ‘value’, { path: currentPath });
}
问题2:跨域Cookie不发送
// 检查SameSite设置
function checkSameSiteIssue() {
// 如果需要跨域发送,不能设置SameSite=Strict
setCookie(‘cross_domain’, ‘value’, {
sameSite: ‘Lax’, // 或 None(需要Secure)
secure: true
});
}
问题3:Cookie过期时间不生效
// 检查时间格式
function checkExpiryIssue() {
// 错误:使用本地时间字符串
// document.cookie = “test=value; expires=Fri, 31 Dec 2023 23:59:59 GMT+8”;

// 正确:使用UTC时间
const date = new Date();
date.setFullYear(date.getFullYear() + 1);
document.cookie = `test=value; expires=${date.toUTCString()}; path=/`;
}
总结
Cookie操作是Web开发中的基础技能,但涉及安全、兼容性等多个方面。关键要点:
安全优先
:始终使用HttpOnly、Secure、SameSite属性
数据限制
:避免存储敏感信息,注意4KB大小限制
兼容性处理
:针对旧浏览器和特殊环境做降级处理
正确编码
:使用encodeURIComponent/decodeURIComponent
路径管理
:合理设置path确保Cookie在正确范围内生效
通过本文提供的完整代码示例和解决方案,开发者可以安全、高效地在网页中实现Cookie的读取、写入和删除操作,并妥善处理各种安全与兼容性问题。