手机端存储用户信息

js localStorage

// 设置带有过期时间的 localStorage 数据项,单位是秒
Storage.prototype.setItemV2 = function(key, value, ttl) {
    if(ttl){
        ttl = ttl * 1000;
    }
    const now = new Date();
    // ttl 是过期时间(单位:毫秒)
    const item = {
        value: value,
        expiry: now.getTime() + ttl,
    };
    localStorage.setItem(key, JSON.stringify(item));
}

// 获取 localStorage 数据项,检查是否过期
Storage.prototype.getItemV2=function(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 item.value;
    } catch (e) {
        localStorage.removeItem(key);
        return null;
    }
}

  

posted on 2024-06-25 15:25  andydaopeng  阅读(1)  评论(0编辑  收藏  举报

导航