📜  保存在本地存储中并过期 - 无论代码示例

📅  最后修改于: 2022-03-11 14:59:04.058000             🧑  作者: Mango

代码示例2
function ls_support(){
    return "localStorage" in window&&window["localStorage"]!==null;
}

function lsset(key,val,exp){
    if(ls_support()){
        if(!exp) exp=600;// = 10 minutes Default
        localStorage[key]=
            JSON.stringify({
                "val":val,
                "exp":~~((new Date()).getTime()/1000)+exp
            });
    }
}

function lsget(key){
    if(ls_support()){
        str=localStorage[key];
        if("undefined"!=typeof(str)&&str.length){
            try{// is json or not
                json=JSON.parse(str);
            }catch(e){// if variable not set via lsset func
                //json.exp=false;// will return null
                return str;// will return original variable
            }
            if(json.exp){// variable setted via lsset func
                if(~~((new Date()).getTime()/1000)>json.exp){// expired
                    delete localStorage[key];
                }else{
                    return json.val;
                }
            }
        }
    }
    return null;
}