Files
wb-java-nc-shop/target/classes/static/js/cookie-utils.js
2026-01-11 18:14:42 +08:00

71 lines
2.0 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Cookie工具类
const CookieUtils = {
/**
* 设置Cookie
* @param {string} name Cookie名称
* @param {string} value Cookie值
* @param {number} days 过期天数默认7天
*/
set(name, value, days = 7) {
const expires = new Date();
expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=/`;
},
/**
* 获取Cookie
* @param {string} name Cookie名称
* @returns {string|null} Cookie值不存在返回null
*/
get(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) {
return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
}
return null;
},
/**
* 删除Cookie
* @param {string} name Cookie名称
*/
remove(name) {
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;`;
},
/**
* 获取JSON格式的Cookie
* @param {string} name Cookie名称
* @returns {any|null} 解析后的JSON对象不存在或解析失败返回null
*/
getJSON(name) {
const value = this.get(name);
if (!value) return null;
try {
return JSON.parse(value);
} catch (e) {
console.error(`Failed to parse cookie ${name}:`, e);
return null;
}
},
/**
* 设置JSON格式的Cookie
* @param {string} name Cookie名称
* @param {any} value 要存储的对象
* @param {number} days 过期天数默认7天
*/
setJSON(name, value, days = 7) {
try {
this.set(name, JSON.stringify(value), days);
} catch (e) {
console.error(`Failed to stringify cookie ${name}:`, e);
}
}
};