/** * 设置带过期时间的数据 * @param {string} key - 存储的键 * @param {array} value - 存储的值 * @param {number} expiryDays - 过期天数 * @returns {void} */ function setItemWithExpiry(key, value, expiryDays) { const _val = typeof value === 'object' ? JSON.stringify(value) : value; const now = new Date(); // 计算过期时间的时间戳(毫秒) const expiryTime = now.getTime() + expiryDays * 24 * 60 * 60 * 1000; const item = { value: _val, expiry: expiryTime, }; localStorage.setItem(key, JSON.stringify(item)); } /** * 获取数据时判断是否过期 * @param {string} key - 存储的键 * @returns {Object|null} */ function getItemWithExpiry(key) { const itemStr = localStorage.getItem(key); if (!itemStr) { return null; } try { const item = JSON.parse(itemStr); const now = new Date(); if (now.getTime() > item.expiry) { console.log('ss'); localStorage.removeItem(key); return null; } return JSON.parse(item.value); } catch (e) { // 解析失败,直接返回null return null; } } const TokenKey = 'GCLS_Token'; export function getSessionID() { const token = getItemWithExpiry(TokenKey); return token ? token.session_id ?? '' : ''; } export function getToken() { const token = getItemWithExpiry(TokenKey); return token; } export function setToken(token) { setItemWithExpiry(TokenKey, token, 10); } export function removeToken() { localStorage.removeItem(TokenKey); } const ConfigKey = 'GCLS_Config'; export function getConfig() { const config = getItemWithExpiry(ConfigKey); return config; } export function setConfig(value) { setItemWithExpiry(ConfigKey, value, 10); } export function removeConfig() { localStorage.removeItem(ConfigKey); }