- 封装初衷-不想每次设置cookie的过期时间都写一遍,比较烦!
class happyCookie {
constructor() { }
/**
* @param {*} cookieName:cookie的名字 string
* @param {*} cookieValue:cookie的值 string
* @param {*} expiresObj:不传/{}/{timeScale:'秒/分/时 日/月/年',timeSize:number}
*/
setCookie(cookieName, cookieValue, expiresObj = null) {
if (!expiresObj) {//用户没有传入第三个参数
//不设置这个时间戳,浏览器会在页面关闭时即将删除该cookie
document.cookie = `${cookieName}=${cookieValue}`;
} else if (Object.keys(expiresObj).length == 0) {//输入的是一个空对象 设置默认过期时间:15分钟
let newDate = new Date();//获取当前的时间对象
let nowTimeStamp = newDate.getTime();//获取当前时间对象的时间戳
nowTimeStamp += (1000 * 60 * 15);
newDate.setTime(nowTimeStamp);
let expires = "expires=" + newDate.toGMTString();
document.cookie = `${cookieName}=${cookieValue};${expires}`;
} else {
let newDate = new Date();//获取当前的时间对象
let nowTimeStamp = newDate.getTime();//获取当前时间对象的时间戳
switch (expiresObj.timeScale) {//判断时间规格
case '秒':
nowTimeStamp += (1000 * expiresObj.timeSize)
break;
case '分':
nowTimeStamp += (1000 * 60 * expiresObj.timeSize)
break;
case '时':
nowTimeStamp += (1000 * 60 * 60 * expiresObj.timeSize)
break;
case '日':
nowTimeStamp += (1000 * 60 * 60 * 24 * expiresObj.timeSize)
break;
case '月':
nowTimeStamp += (1000 * 60 * 60 * 24 * 30 * expiresObj.timeSize)
break;
case '年':
nowTimeStamp += (1000 * 60 * 60 * 24 * 30 * 12 * expiresObj.timeSize)
break;
default:
break;
}
newDate.setTime(nowTimeStamp)
let expires = "expires=" + newDate.toGMTString();
document.cookie = `${cookieName}=${cookieValue};${expires}`;
}
}
getCookie(cookieName) {
let name = cookieName + "=";
let ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
delCookie(cookieName) {
document.cookie = cookieName + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
export {
happyCookie
}