functionsetCookie(name,value,maxAge,path,domain,secure) { //检测flag var cookieinfo = { name: name, value: value, maxAge: maxAge, path: path, domain: domain, secure: secure }; var res = '';
//验证值 for(key in cookieinfo) { var val = cookieinfo[key]; if (key == 'path') { if (!val) { continue; }elseif (typeof val != 'string') { thrownewError('Error: path must be an string!'); } }elseif (key == 'domain') { if (!val) { continue; }elseif (typeof val != 'string') { thrownewError('Error: domain must be an string!'); } }elseif (key == 'secure') { if (!val) { continue; }elseif (typeof val != 'boolean') { thrownewError('Error: secure must be an boolean!'); } }elseif (val == '' || val == undefined || val == null) { thrownewError('Error:' + key + ' not a null value!'); } }
//赋值 for (var key in cookieinfo) { var val = cookieinfo[key]; if (val == undefined) { continue; } if (key == 'value') { continue; } if (key == 'name') { res += cookieinfo['name'] + '=' + encodeURIComponent(cookieinfo['value']) + ';'; }elseif (key == 'maxAge') { res += 'max-age' + '=' + cookieinfo['maxAge'] + ';'; } elseif (key == 'secure' && cookieinfo['secure'] === true) { res += 'secure;'; } else { res += key + '=' + val + ';'; } }
if (res) { document.cookie = res; } } //例如: setCookie('title',document.title,60*60*24*7,'/','127.0.0.1',secure);
functiongetCookie(isAll,name) { var tisAll = isAll; var tname = name;
if (typeof tisAll != 'boolean') { thrownewError('Error: tisAll not an boolean!'); } if (!tisAll) { if (tname == 'undefined' || tname == null || tname == '' || typeof tname == 'object' || typeof tname == 'function') { thrownewError('Error: name not an object or function or undefined!'); } } var cookie = document.cookie; var cookies = cookie.split(';'); var value = ''; var allObj = {}; for(var i=0;i<cookies.length;i++) { var vals = cookies[i].split('='); var allKey = vals[0].trim(); var allVal = decodeURIComponent(vals[1]); if (allKey == '' && allVal == '') { continue; } else { if (tisAll) { allObj[allKey] = allVal; } else { if (tname == allKey) { value = allVal; } } } } if (!tisAll && value == '') { thrownewError('Error:' + tname + ' not found!'); }
if (tisAll) { for (var key in allObj) { if (key == '' && allObj[key] == 'undefined') { thrownewError('Error: all cookie not found!'); } } }
var res = tisAll ? allObj : value; return res; } //例如:上面的cookie值 console.log(getCookie(false,'title')); // 你好啊
functionremoveCookie(name) { if (name == '' || name == undefined || name == null) { thrownewError('Error: name not an null!'); } var cookie = document.cookie; var cookies = cookie.split(';'); var res; for(var i=0;i<cookies.length;i++) { var vals = cookies[i].split('='); var allKey = vals[0].trim(); if (name == allKey) { res = true; } } if (!res) { thrownewError('Error:' + name +' not found!'); } document.cookie = name + '=' + '' + ';max-age=0'; } //例如:删除上面的title removeCookie('title');