/*下面代码来自《Javascript高级程序设计》,封装了浏览器中常用cookie操作*/
cookieUtil = {
//获取cookie
"get" : function(name){
if(typeof name !== "string"){
return "";
}
var cookieName = encodeURIComponent(name) + '=',
cookieStart = document.cookie.indexOf(cookieName),
cookieValue = "",
cookieEnd = -1;
if(cookieStart > -1){
cookieEnd = document.cookie.indexOf(";", cookieStart);
if(cookieEnd == -1){
cookieEnd = document.cookie.length;
}
cookieValue = document.cookie.slice(cookieStart + cookieName.length, cookieEnd);
}
return cookieValue;
},
//设置cookie
"set" : function(name, value, expires, maxAge, path, domain, secure){
var cookieText = encodeURIComponent(name) + '=' + encodeURIComponent(value);
if(expires instanceof Date){
cookieText += "; expires=" + expires.toGTMString();
}
if(maxAge){
cookieText += "; max-age=" + maxAge;
}
if(path){
cookieText += "; path=" + path;
}
if(domain){
cookieText += "; domain=" + domain;
}
if(secure){
cookieText += "; secure";
}
document.cookie = cookieText;
},
//清除cookie
"unset" : function(name, expires, maxAge, path, domain, secure){
this.set(name, "", new Date(0), 0, path, domain, secure);
}
};
/*
cookie
1.document.cookie
2.一个名值对(加与其相关的配置)即为一个cookie
3.cookie的配置信息
expires GTM时间,过期时间,设置cookie在某月某日某时刻到期
max-age 秒,cookie在多少秒后过期
domain
path
secure 设置secure后只有在协议为https是才能使用cookie
httpOnly
在浏览器中使用时,配置信息必须与名值对同时设置
4.浏览器中通过document.cookie访问到的cookie不包含cookie的配置信息
5.多个cookie之间,cookie与其配置之间用引号加一个空格隔开
6.最好为cookie的键和值使用url编码
7.如果没有为cookie设置expires或max-age,则cookie被视为会话cookie,当浏览器关闭后cookie即被删除,但关闭标签页cookie不会被删除
8.max-age的优先级高于expires
*/