/** * 设置带过期时间的数据 * @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) { 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); } /** * 设置本地存储 * @param {string} key - 存储的键 * @param {any} value - 存储的值 */ export function setLocalStore(key, value) { try { if (value === undefined) { localStorage.removeItem(key); return; } const toStore = typeof value === 'string' ? value : JSON.stringify(value); localStorage.setItem(key, toStore); } catch (e) { // 序列化或存储失败时退回到字符串存储,若仍失败则忽略 try { localStorage.setItem(key, String(value)); } catch (_) { /* noop */ } } } /** * 获取本地存储 * @param {string} key - 存储的键 * @returns {any} 返回存储的值 */ export function getLocalStore(key) { const value = localStorage.getItem(key); try { if (value) { return JSON.parse(value); } return null; } catch (e) { return value; } } /** * 移除本地存储 * @param {string} key - 存储的键 */ export function removeLocalStore(key) { localStorage.removeItem(key); }