/**
* @method getCookie 獲取指定name的cookie值
* @param {name} 需要獲取的cookie的name值
* @return {String} 如果該cookie存在就返回cookie值,不存在就返回空
*/
GcookieApi.prototype.getCookie=function(name){
var cookieStr=document.cookie;
if(cookieStr.length>0){
var start =cookieStr.indexOf(name+"=");
if(start>-1){
start+=name.length+1;
var end = cookieStr.indexOf(";",start);
if(end===-1){
end=cookieStr.length;
}
}
return decodeURIComponent(cookieStr.slice(start,end));
}
return "";
}
/**
* @method getAllCookies 返回跟js同源的所有的cookie
* @return {String}
*/
GcookieApi.prototype.getAllCookies=function(){
return document.cookie;
}
/**
* @method getCookiesByJson 以json的形式返回cookie。
* @return {JSON} 將cookie已json的形式返回
*/
GcookieApi.prototype.getCookiesByJson=function(){
//cookie中值不能直接爲分號(;),document.cookie也不會返回有效期、域名和路徑,所以可以使用分號(;)分隔cookie
//使用JSON.parse的時候,字符串形式的對象。名和值必須使用雙引號包裹,如果使用單引號就會報錯 比如 JSON.parse("{'a':'1'}")是錯誤的 應該爲JSON.parse('"a":"1"');
var cookieArr =document.cookie.split(";");
var jsonStr='{';
for(var i=0;i<cookieArr.length;i++){
var cookie=cookieArr[i].split("=");
jsonStr+='"'+cookie[0].replace(/\s+/g,"")+'":"'+decodeURIComponent(cookie[1])+'",';
}
jsonStr=jsonStr.slice(0,-1);
jsonStr+='}';
return JSON.parse(jsonStr);
}
/**@method deleteCookie 如果要刪除一個cookie,必須域名和path都跟已有的cookie相同
* @param {String} name cookie名name
* @param {String} value cookie值value
* @param {Number} time cookie的有效時間,比如2016-01-01 00:00:00,如果不設置expres爲session。關閉瀏覽器後或者過了session時間就清除cookie,
* @param {String} domain cookie的域名,默認爲js文件所在域名
* @param {String} path cookie路徑,默認爲當前路徑js文件所在路徑
* @return {Undefined}
*/
GcookieApi.prototype.setCookie=function(name,value,time,domain,path){
var str=name+"="+encodeURIComponent(value);
if(time){
var date = new Date(time).toGMTString();
str+=";expires="+date;
}
str=domain?str+";domain="+domain : str;
str=path?str+';path='+path :str;
document.cookie=str;
}
/**
* @description 要刪除一個cookie,比如domain和path完全相同。如果設置cookie時沒有設置domain和path,則刪除時也不需要設置這兩個值,如果設置了則刪除時就需要傳入這兩個值
* @param {String} name [cookie名]
* @param {String} domain [cookie domian值]
* @param {String} path [cookie 路徑]
* @return {undefined} [返回undefined]
*/
GcookieApi.prototype.deleteCookie=function(name,domain,path){
var date = new Date("1970-01-01");
var str=name+"=null;expires="+date.toGMTString();
str=domain ? str+";domain="+domain : str;
str=path ? str+";path="+path : str;
document.cookie=str;
}
GcookieApi.prototype.deleteAllCookie=function(){
var cookieJson=this.getCookiesByJson(),
str="",
date = new Date("1970-01-01");
for(var i in cookieJson){
str=i+"=null;expires="+date.toGMTString();
}
document.cookie=str;
}