JS之封装cookie操作

原生js中,我们通过document.cookie可以获取cookie,这样我们可以不用考虑兼容性,但是增,删,查我们最好通过封装的形式把他们区分开来,使得我们能够像操作对象一样去操作cookie,这样使用起来也直观方便,底层还是基于document.cookie来操作。

下面直接上代码加注释:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//用闭包将代码包起来,避免引入时污染全局作用域
(function(global){
//获取cookie对象,格式化成对象形式
function getCookiesObj(){
var cookies = {};
if(document.cookie){
var objs = document.cookie.split(';');
for(var i in objs){
var index = objs[i].indexOf('=');
var key = objs[i].substr(0,index);
var value = objs[i].substr(index+1,objs[i].length);
cookies[key] = value;
}
}
return cookie;
}
//获取cookie
function get(key){
return decodeURIComponent(getCookiesObj()[key]) || null;
}
//设置cookie
function set(name,value,opts){
//opts: maxAge,path,domain,secure
if(name && value){
var cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
if(opts){
if(opts.maxAge){
cookie += ';max-age=' + opts.maxAge;
}
if(opts.path){
cookie += ';max-age=' + opts.path;
}
if(opts.domain){
cookie += ';max-age=' + opts.doamin;
}
if(opts.secure){
cookie += ';max-age=' + opts.secure;
}
}
document.cookie = cookie;
return cookie;
}else{
return '';
}
}
function remove(key){
if(getCookiesObj()[key]){
document.cookie = key + '=;max-age=0';
}
}
function clear(){
var cookies = getCookiesObj();
for(var i in cookies){
document.cookie = cookies[i] + '=;max-age=0';
}
}
global['cookie'] = {
'getCookiesObj': getCookiesObj,
'set': set,
'get': get,
'remove': remove,
'clear': clear
}
})(window)

封装好后,我们只要导入这个文件,就可以用全局变量的方式去操作cookie了!