How do I create and read a value from cookie?

前端 未结 19 1727
梦如初夏
梦如初夏 2020-11-21 04:42

How can I create and read a value from a cookie in JavaScript?

19条回答
  •  忘掉有多难
    2020-11-21 05:16

    I use the following functions, which I have written by taking the best I have found from various sources and weeded out some bugs or discrepancies.

    The function setCookie does not have advanced options, just the simple stuff, but the code is easy to understand, which is always a plus:

    function setCookie(name, value, daysToLive = 3650) { // 10 years default
      let cookie = name + "=" + encodeURIComponent(value);
      if (typeof daysToLive === "number") {
        cookie += "; max-age=" + (daysToLive * 24 * 60 * 60);
        document.cookie = cookie + ";path=/";
      }
    }
    function getCookie(name) {
      let cookieArr = document.cookie.split(";");
      for (let i = 0; i < cookieArr.length; i++) {
        let cookiePair = cookieArr[i].split("=");
        if (name == cookiePair[0].trim()) {
          return decodeURIComponent(cookiePair[1].trim());
        }
      }
      return undefined;
    }
    function deleteCookie(name) {
      setCookie(name, '', -1);
    }
    

提交回复
热议问题