常用代码 - 操作cookie ¶
作者:KK
发表日期:2016.12.6
我也是从别处拷来的,这是一个独立无任何其它类库依赖的函数,你可以直接粘贴到项目中,或整合到你的工具类库中使用,使用示例在下面
function cookie(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
// CAUTION: Needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason...
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
}
使用例子:
//设置cookie
cookie('key1', 'val1');
//读cookie
console.log('key1'); // val1
//删除cookie
cookie('key1', null);
console.log('key1'); // null
//指定过期时间为7天后和其它选项
var date = new Date();
date.setDate(date.getDate() + 7);
cookie('key2', 'val2', {
expires : date, //也可以是一个数字的unix时间戳
domain : document.domain, //指定有效域名
path : '/user' // 指定有效目录
});