cookie屬性,有效期和做用域

/*
* cookieStorage API
* @maxage 有效期
* path 做用域
* */

 

function cookieStorage (maxage, path) {    var cookie = (function(){        var cookie = {};
var all = document.cookie; // 獲取所有的cookie的信息
// 若是爲空字符串就返回空對象
if (all === "")
return cookie;
// 分離出名/值對
var list =all.split("; ");
// 遍歷每一個cookie
for(var i = 0; i < list.length; i++) {
var cookie = list[i];
console.log(cookie);
var p = cookie.indexOf("="); // 查找第一個"="符號
var name = cookie.substring(0, p); // 獲取cookie的名字
var value = cookie.substring(p + 1); // 獲取cookie對應的值
value = decodeURIComponent(value); // 將名值對存儲到對象中
if (name === "userId") {
continue;
}
cookie[name] = value;
}
return cookie;
}());
// 將全部cookie的名字存儲到一個數組中
var keys = [];
for (var key in cookie) keys.push(key);

// 定義存儲API公共的屬性和方法
// 存儲的cookie的個數
this.length = keys.length;
console.log(this.length);

//返回第n個cookie的名字,若是n越界則返回null
this.key = function(n) {
if(n < 0 || n > keys.length) {
return null
}
return keys[n];
};

//返回指定名字的cookie值,若是不存在則返回null

this.getItem = function(name) {
return cookie[name] || null;
};

// 存儲cookie值
this.setItem = function(key, value) {
if(! (key in cookie)) {
keys.push(key);
this.length++;
}
//將該名/值對數據存儲到cookie對象中
cookie[key] = value;
// 開始正式設置cookie
//首先將要存儲的cookie的值進行編碼同事建立一個 "名字=編碼後的值"形式的字符串
var cookie = key + "=" +encodeURIComponent(value);
// 將cookie的屬性也加入到該字符串中
if(maxage) cookie += "; max-age=" + maxage;
if(path) cookie += "; path=" + path;

//經過document.cookie屬性來設置cookie
document.cookie = cookie;
};

// 刪除指定的cookie
this.removeItem = function(key) {
if( ! (key in cookie)) {
return;
}
//從內部維護的cookie組刪除指定的cookie
delete cookie[key];

//同時將cookie中的名字也在內部的數組中刪除
for( var i=0; i < keys.length; i++) {
if(keys[i] === key) {
keys.splice(i, 1);
break;
}
}
this.length --;
// 經過將該cookie值設置爲空字符串以及將有效期設置爲0來刪除指定的cookie
document.cookie = key + "=; max-age=0";
};

//刪除全部的cookie
this.clear = function () {
//循環全部的coolie的名字,並將cookie刪除
for(var i = 0; i < keys.length; i++ )
document.cookie = keys[i] + "=; max-age=0";
// 重置全部的內部狀態
cookie = {};
key = [];
this.length = 0;

};
}

推薦前端學習羣:fe html5/css3/js/jq/nodejs/div 羣號:339840649
相關文章
相關標籤/搜索