UNPKG

jbd

Version:
122 lines (108 loc) 2.93 kB
/** * ========================================== * Name: Cookie * Author: Buddy-Deus * CreTime: 2014-11-20 * Description: Cookie操作 * Log * 2015-06-08 优化模块结构 * 2016-04-25 优化代码 * ========================================== */ jBD.define(function (module, exports, require) { "use strict"; let API; API = { /** * 获取cookie值数组 * * @public * @returns {Array} */ Query: () => { let data = document.cookie, rxp = /(\w*)=([^;]*)/ig, result = [], tmp; while (tmp = rxp.exec(data)) { if (tmp[0]) result.push({key: tmp[0], value: tmp[1]}); } return result; }, /** * 获取值 * * @public * @param {string} name * @returns {string} */ Get: name => { name = jBD.isString(name, true) ? escape(name) : ""; let data = document.cookie, rxp = new RegExp(name + "=([^;]*)", "ig"), result = ""; if ((data = rxp.exec(data)) && data[0]) result = data[1]; return result; }, /** * 设置值 * * @public * @param {string} name * @param {string} value * @param {object} [opt] * @param {boolean} [opt.secure=false] * @param {number} [opt.seconds=0] * @param {string} [opt.domain=''] * @parma {string} [opt.path=''] * @returns {object} */ Set: (name, value, opt) => { if (!jBD.isString(name)) return ""; let data = document.cookie, start = data.indexOf(name), end = data.indexOf(";", start); value = name + "=" + (jBD.isString(value) ? escape(value) : ""); if (start == -1) data = (data.length > 1 ? data + ";" : "") + value; else data = data.replace(data.substring(start, (end > start ? end : data.length)), value); if (jBD.isObject(opt)) { if (jBD.isNumber(opt.seconds) && opt.seconds > 0) { let dt = new Date(); dt.setTime(dt.getTime() + opt.seconds); value += "; expires=" + dt.toGMTString(); } if (jBD.isString(opt.path)) value += "; path=" + opt.path; if (jBD.isString(opt.domain)) value += "; domain=" + opt.domain; if (opt.secure === true) value += "; secure"; } document.cookie = value; return data; }, /** * 删除值 * * @public * @param {string} name * @param {object} [opt] * @param {boolean} [opt.secure=false] * @param {number} [opt.seconds=0] * @param {string} [opt.domain=''] * @parma {string} [opt.path=''] * @returns {object} */ Del: (name, opt) => API.Set(name, "", opt), /** * 清除全部 * * @public * @param {object} [opt] * @param {boolean} [opt.secure=false] * @param {number} [opt.seconds=0] * @param {string} [opt.domain=''] * @parma {string} [opt.path=''] * @returns {Object} */ Clear: opt => jBD.each(API.Query(), d => API.Del(d.key, opt)) }; return API; }, {module: module, exports: this}, [], "Cookie");