手書きjquery.クッキーカード
17570 ワード
/**
* cookie
* @param name
* @param value
* @param config expires:(Number|Date) ; , ; Cookie ;
path:(String) Cookie ;
domain:(String) Cookie ;
secure:(Boolean) true, Cookie , :HTTPS;
*/
function addCookie(name,value,config = {
expires: null,
path: null,
maxAge: null,
domain: null,
secure: true,
httpOnly: true
}) {
value = $.cookie.json ? JSON.stringify(value) : value;
value = $.cookie.raw ? value : encodeURIComponent(value);
let cookieStr = name + '=' + value;
if(config) {
if(config.expires) {
if(typeof config.expires === 'number') {
const date=new Date();
date.setTime(date.getTime()+config.expires*86400000);
cookieStr += '; expires=' + date.toUTCString();
}else if(config.expires instanceof Date) {
cookieStr += '; expires=' + config.expires.toUTCString();
}else {
throw new Error('expires Number Date ')
}
}
cookieStr += config.path ? '; path='+config.path : '';
cookieStr += config.maxAge ? '; max-age='+config.maxAge : '';
cookieStr += config.domain ? '; domain=' + config.domain : '';
cookieStr += config.secure ? '; secure' : '';
cookieStr += config.httpOnly ? ';httpOnly' : '';
}
document.cookie = cookieStr;
}
/**
* cookie
* @param name
* @returns {
{}|*}
*/
function getCookie(name) {
let cookieStrArr = document.cookie.split(';');
let cookieObj = {
};
cookieStrArr.forEach(cookieStr => {
let temp = cookieStr.split('=');
let key = temp[0].trim();
let value = temp[1];
value = $.cookie.json ? JSON.parse(value) : value;
value = $.cookie.raw ? value : decodeURIComponent(value);
cookieObj[key] = value;
});
if(name) {
return cookieObj[name];
}else {
return cookieObj;
}
}
/**
* cookie
* @param name
* @param config
*/
function removeCookie(name,config) {
// cookie
config.expires = -1;
addCookie(name,null,config);
}
$.extend({
/**
* , cookie
* @param name
* @param value
* @param config
*/
cookie: function (name,value,config) {
if(value) {
addCookie(name,value,config);
}else if(value == null) {
removeCookie(name,null,config);
}else {
getCookie(name);
}
},
/**
* cookie
* @param name
* @param config
* @returns {boolean}
*/
removeCookie(name,config) {
if(getCookie(name)) {
removeCookie(name,config);
return true;
}else {
return false;
}
}
});
/**
* :false。
, cookie ( encodeURIComponent ,decodeURIComponent )。 raw:true :
* @type {boolean}
*/
$.cookie.raw = false;
/**
* :false。
* cookie json , JSON.stringify JSON.parse 。
* @type {boolean}
*/
$.cookie.json = false;