Cookie 的简单封装

对于前端工程师来说,在项目开发过程中 cookie 的相关操作还是经常会遇到的,但是直接用原生的方法代码显得不够简洁和语义化,在项目里我们稍稍封装一下,类似于 Storage对象的API,然后在使用时就会方便很多,如下:

/**
 * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
 * docCookies.getItem(name)
 * docCookies.removeItem(name[, path], domain)
 * docCookies.hasItem(name)
 * docCookies.keys()
 * */

let 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; 
    }

    let 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);
  },
  keys: function () {
    let aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);

    for (let nIdx = 0; nIdx < aKeys.length; nIdx++) { 
      aKeys[nIdx] = decodeURIComponent(aKeys[nIdx])
    }

    return aKeys
  }
}

 

使用参数: 

docCookies.setItem("test0", "Hello world!");
docCookies.setItem("test1", "Unicode test: \u00E0\u00E8\u00EC\u00F2\u00F9", Infinity);
docCookies.setItem("test2", "Hello world!", new Date(2020, 5, 12));
docCookies.setItem("test3", "Hello world!", new Date(2027, 2, 3), "/blog");
docCookies.setItem("test4", "Hello world!", "Sun, 06 Nov 2022 21:43:15 GMT");
docCookies.setItem("test5", "Hello world!", "Tue, 06 Dec 2022 13:11:07 GMT", "/home");
docCookies.setItem("test6", "Hello world!", 150);
docCookies.setItem("test7", "Hello world!", 245, "/content");
docCookies.setItem("test8", "Hello world!", null, null, "example.com");
docCookies.setItem("test9", "Hello world!", null, null, null, true);
docCookies.setItem("test1;=", "Safe character test;=", Infinity);
 
console.log(docCookies.keys().join("\n"));
console.log(docCookies.getItem("test1"));
console.log(docCookies.getItem("test5"));

docCookies.removeItem("test1");
docCookies.removeItem("test5", "/home");

console.log(docCookies.getItem("test1"));
console.log(docCookies.getItem("test5"));
console.log(docCookies.getItem("unexistingCookie"));
console.log(docCookies.getItem());
console.log(docCookies.getItem("test1;="));

 

 

摘自:MDN 里 Document.cookie

 

posted @ 2019-11-11 17:24  cmyoung  阅读(257)  评论(0编辑  收藏  举报