localStorage 设置过期时间

发布于 2020-11-11  67 次阅读


//保存localStorage
function set(key, value, days) {
    // 设置过期原则
    if (!value) {
        localStorage.removeItem(key)
    } else {
        let Days = days || 7; // 默认保留7天
        let exp = new Date();
        localStorage[key] = JSON.stringify({
            value,
            expires: exp.getTime() + Days * 24 * 60 * 60 * 1000
        })
    }
}
//取出localStorage
function get(name) {
    try {
        let o = JSON.parse(localStorage[name]);
        if (!o || o.expires < Date.now()) {
            return null
        } else {
            return o.value
        }
    } catch (e) {
        // 兼容其他localstorage
        return localStorage[name]
    } finally {
    }
}

一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。