js對cookie的操作比較簡單,關鍵是要設計一個通用的工具類來設定cookie的生命周期和路徑等。
使用實例
// 讀取cookie var cookieValue = Cookie.get('cookie-name'); // 添加cookie Cookie.set('cookie-name', 'cookie-value', options); // 刪除cookie Cookie.remove('cookie-name', options);
函數定義
包括cookie的讀取(get
)、添加(set
)、刪除(remove
)操作
var Cookie = { /** * 返回指定name的cookie * @param {String} name 要檢索cookie的名稱 * @param {Function|Object} [options] 一個對象包含一個或多個cookie選項; * 1.當options是函數時,轉換函數返回值。 * 2.當options是對象,raw被設置為true時,cookie值不是URI解碼。 * @returns {*} */ get: function (name, options) { validateCookieName(name); if (typeof options === 'function') { options = {converter: options}; } else { options = options || {}; } var cookies = parseCookieString(document.cookie, !options['raw']); return (options.converter || same)(cookies[name]); }, /** * 根據給定的名稱和值設置一個cookie * @param {string} name cookie的名稱 * @param {*} value 設置cookie的值 * @param {Object} [options] 包含cookie選項的對象: * path (a string) 默認根目錄 * domain (a string) 默認當前域名的domain * expires (number or a Date object) 默認30天 * secure (true/false) 當屬性設置為true時,cookie只有在https協議下才能上傳到服務器。 * raw (true/false). 如果設置為true,cookie不應該在設置之前URI編碼。 * @returns {string} 創建的cookie字符串 */ set: function (name, value, options) { validateCookieName(name); options = options || {}; var expires = options['expires']; if (typeof expires === 'undefined') { // 默認30天有效期 expires = 30; } var domain = options['domain'] || document.domain; var path = options['path'] || '/'; if (!options['raw']) { value = encode(String(value)); } var text = name + '=' + value; // expires var date = expires; if (typeof date === 'number') { date = new Date(); date.setDate(date.getDate() + expires); } if (date instanceof Date) { text += '; expires=' + date.toUTCString(); } // domain if (isNonEmptyString(domain)) { text += '; domain=' + domain; } // path if (isNonEmptyString(path)) { text += '; path=' + path; } // secure if (options['secure']) { text += '; secure'; } document.cookie = text; return text; }, /** * 通過將cookie有效期設置成一個過去的時間來移除cookie * @param {string} name 將要移除的cookie名 * @param options cookie配置項,參考set方法 * @returns {string} 創建的cookie字符串 */ remove: function (name, options) { options = options || {}; options['expires'] = new Date(0); return this.set(name, '', options); } };
最后定義內部使用的一些方法,比如驗證cookie,解析cookie等。
var decode = decodeURIComponent; var encode = encodeURIComponent; // Helpers function isString(o) { return typeof o === 'string'; } function isNonEmptyString(s) { return isString(s) && s !== ''; } function validateCookieName(name) { if (!isNonEmptyString(name)) { throw new TypeError('Cookie name must be a non-empty string'); } } function same(s) { return s; } function parseCookieString(text, shouldDecode) { var cookies = {}; if (isString(text) && text.length > 0) { var decodeValue = shouldDecode ? decode : same; var cookieParts = text.split(/;\s/g); var cookieName; var cookieValue; var cookieNameValue; for (var i = 0, len = cookieParts.length; i < len; i++) { // Check for normally-formatted cookie (name-value) cookieNameValue = cookieParts[i].match(/([^=]+)=/i); if (cookieNameValue instanceof Array) { try { cookieName = decode(cookieNameValue[1]); cookieValue = decodeValue(cookieParts[i] .substring(cookieNameValue[1].length + 1)); } catch (ex) { // Intentionally ignore the cookie - // the encoding is wrong } } else { // Means the cookie does not have an "=", so treat it as // a boolean flag cookieName = decode(cookieParts[i]); cookieValue = ''; } if (cookieName) { cookies[cookieName] = cookieValue; } } } return cookies; }
將上述代碼拷貝到一個js文件中,引入js文件即可訪問。
下載地址:cookie.js