JS对cookie的读取、修改、删除
2020-10-21 本文已影响0人
忘了呼吸的那只猫
读取cookie转化为JS对象
function getCookie() {
var jsCookie = {};
var cookie = document.cookie;
if (cookie === '') {
return jsCookie;
}
//cookie是以分号和一个空格隔开的一系列键值对
var cookieList = cookie.split('; ')
for (var i = 0; i < cookieList.length; i++) {
//取出一个cookie数组中的元素
var item = cookieList[i];
//找出每一个元素中“=”所在的位置
var index = item.indexOf('=');
//以下分开“=”前后作为key和value
var name = item.substring(0, index);
//解码
name = decodeURIComponent(name);
var value = item.substring(index + 1);
value = decodeURIComponent(value);
//写入jsCookie对象中,自动添加新增
jsCookie[name] = value;
}
return jsCookie;
}
修改cookie
function setCookie(name, value, expires, path, domain, secure) {
var cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
if (expires) {
cookie += '; expires=' + expires;
}
if (path) {
cookie += '; path=' + path;
}
if (domain) {
cookie += '; domain=' + domain;
}
if (secure) {
cookie += '; secure=' + secure;
}
document.cookie = cookie;
}
删除cookie
function deleteCookie(name, path, domain) {
document.cookie = 'name=' + name + ';
path=' + path + ';
domain=' + domain + ';
max-age=0';
}//name+path+domain即可确定唯一cookie,将其max-age设置为0即等同于删除。