簡易封裝document.cookie輔助函數

MDN官網提供的cookie操作的輔助函數:

document.cookie

MDN document.cookie讀寫器函數(源碼):

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  https://developer.mozilla.org/en-US/docs/DOM/document.cookie
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path], domain)
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
  // 獲取  
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[-.+*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  // 設置/添加
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  // 移除
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  },
  // 判斷是否存在
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[-.+*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  // 獲取所有可用cookie的key列表
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

 

簡易代碼實現的隨筆:

/**
 * 獲取單個cookie的值
 * @param {string} key - cookie的鍵名
 * @return {(string | object)} 
 */
function getCookieItem(key) {
  const cookies = document.cookie ? document.cookie.split('; ') : [];
  const size = cookies.length;
  let result = {};
  for (let i = 0; i < size; i++) {
    const [k, v] = cookies[i].split('=');
    const name = decode(k);
    if (name === key) {
      result = decode(v);
      break;
    }
    if (key === undefined && v) {
      result[name] = decode(v);
    }
  }
  return result;
}

/**
 * cookie配置項的類型定義
 * @typedef {Object} CookieOptions
 * @prop {string} path - 路徑
 * @prop {string} domain - 域名
 * @prop {number} maxAge - cookie的有效期
 * @prop {(string | number | Date)} expires - UTC字符串(沒有設置,則會在會話結束時過期)
 * @prop {boolean} secure - 只允許https的協議傳輸
 */

/**
 * 添加/設置cookie
 * @param {string} key - cookie的鍵名
 * @param {string} value - cookie的值
 * @param {CookieOptions} [options={}] - cookie項的相關配置
 * @return {boolean}
 */
function setCookieItem(key, value, options = {}) {
  if (!key) {
    return false;
  }
  let expires = '';
  if (options.expires) {
    switch(options.expires.constructor) {
      case Number:
        expires = options.expires === Infinity ? '; expires=Fri, 31 Dec 9999 23:59:59 GMT' : '; max-age=' + options.expires;
        break;
      case String:
        expires = '; expires=' + options.expires;
        break;
      case Date:
        expires = '; expires=' + options.expires.toUTCString();
        break;
    }
  }
  document.cookie = [
      encode(key),
      '=',
      encode(value),
      expires, 
      options.path ? '; path=' + options.path : '',
      options.domain ? '; domain=' + options.domain : '',
      options.secure ? '; secure' : '',
  ].join('');
  return true;
}

/**
 * 移除單個cookie記錄
 * @param {string} key - cookie的鍵名
 * @param {CookieOptions} [options={}] - cookie項的相關配置
 * @return {boolean} 
 */
function removeCookieItem(key, options = {}) {
  setCookieItem(key, '', { ...options, expires: -1 });
  return !getCookieItem(key);
}

/**
 * 編碼URI字符串
 * @param {(string | number | boolean)} uriComponent - 未編碼的資源標識符的部分字符
 * @return {string} 
 */
function encode(uriComponent) {
  return window.encodeURIComponent(uriComponent);
}

/**
 * 解碼URI字符串
 * @param {string} encodedURIComponent - 編譯後的資源標識符字符串
 * @return {string}
 */
function decode(encodedURIComponent) {
  return window.decodeURIComponent(encodedURIComponent);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章