JavaScript data storage Cookie article

  • 2021-07-01 06:31:16
  • OfStack

1. What is cookie?
Answer: cookie is used to store session information on the client.
2. What are the components of cookie?
① Name: 1 only 1 determines the name of cookie. Case sensitivity is recommended. The name of cookie must be URL encoded.
Value: The string value stored in cookie. Value must be URL encoded.
③ Domain: For which domain cookie is valid. This cookie information will be included in all requests sent to this domain. This value can contain subdomains (subdomain, such as www. wrox. com) or not (E. G. wrox. com is valid for all subdomains of wrox. com). If it is not explicitly set, this domain will be considered to be from the domain where cookie is set.
Path: For that path in the specified domain, cookie should be sent to the server. For example, you can specify that cookie can only be accessed from http://www. wrox. com/books/, so the page of http://www. wrox. com will not send cookie information, even if the requests are all from the same domain.
⑤ Invalidation time: a timestamp indicating when cookie should be deleted. By default, all cookie are deleted at the end of the browser session; However, you can also set your own deletion time. This value is a date in GMT format (Wdy, DD-Mon-YYYY HH: MM: SS GMT), which specifies the exact time when cookie should be deleted. Therefore, cookie
Can still be saved on the user's machine after the browser is closed. If the expiration date you set is a previous time, cookie will be deleted immediately.
⑥ Security flag: After being specified, cookie will only be sent to the server when connecting with SSL. For example, cookie messages can only be sent to https://www.wrox.com, while requests from http://www.wrox.com cannot be sent to cookie.
3. Give an example of cookie?
The following is a complete example of cookie, which we will break down:
Set-Cookie: name=value; expires=Mon, 22-Jan-07 07:10:24 GMT; domain=.wrox.com; path=/; secure
① Name: name string representation
② Value: value string representation
③ Expired time: Mon, 22-Jan-07 07: 10:24 GMT
④ Domain name:. wrox. com
⑤ Path: Current directory/
⑥ Safety sign: secure
4. How to operate cookie?


  var CookieUtil = {
    //  Settings cookie
    set : function (name, value, expires, domain, path, secure) {
      var cookieText = "";
      cookieText += encodeURIComponent(name) + "=" + encodeURIComponent(value);
      if (expires instanceof Date) {
        cookieText += "; expires=" + expires.toGMTString();
      }
      if (path) {
        cookieText += "; path=" + path;
      }
      if (domain) {
        cookieText += "; domain=" + domain;
      }
      if (secure) {
        cookieText += "; secure";
      }
      document.cookie = cookieText;
    },
    // name=value; expires=expiration_time; path=domain_path; domain=domain_name; secure
    //  Get cookie
    get : function (name) {
      var cookieName = encodeURIComponent(name) + "=",
        cookieStart = document.cookie.indexOf(cookieName),
        cookieValue = "";
      if (cookieStart > -1) {
        var cookieEnd = document.cookie.indexOf (";", cookieStart);
        if (cookieEnd == -1) {
          cookieEnd = document.cookie.length;
        }
        cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
      }
      return cookieValue; 
    },
    //  Delete cookie
    unset : function (name, domain, path, secure) {
      this.set(name, "", Date(0), domain, path, secure);
    }
  };
  //  Test 
  CookieUtil.set("name", "zhang");
  var name = CookieUtil.get("name");
  alert(name);  // zhang
  CookieUtil.unset("name");
  alert(CookieUtil.get("name")); //  Empty 

5. Limitations of cookie
① The amount of stored data is limited
Ensure that the information stored in cookie can only be accessed by approved recipients, but cannot be accessed by other domains
③ Limited safety
6. To solve the problem of small amount of data storage in cookie, we put forward the concept of sub-cookie. That is, multiple pieces of data are stored in each cookie value, using " & "Separate.


  var SubCookieUtil = {
    /**  Settings 1 Complete cookie
    *  param name :  Denote cookie Name of, required 
    *  param subCookies :  Denote cookie Is the value of 1 Objects, required 
    *  param expires :  Denote cookie You can not fill in the expiration time of 
    *  param domain :  Denote cookie The domain name of, you can not fill in 
    *  param path :  Denote cookie You can not fill in the path of 
    *  param secure :  Denote cookie Safety sign of, may not fill in 
    *  eg : SubCookieUtil.setAll("info", { name : "zhang", age : 23});
    **/
    setAll : function (name, subCookies, expires, domain, path, secure) {
      var cookieText = "", subName, cookieParts = [];
      cookieText += encodeURIComponent(name) + "=";
      for(subName in subCookies) {
        cookieParts.push(encodeURIComponent(subName) + "=" + encodeURIComponent(subCookies[subName]));
      }
      if (cookieParts.length > 0) {
        cookieText += cookieParts.join("&");
        if (expires instanceof Date) {
          cookieText += "; expires=" + expires.toGMTString();
        }
        if (path) {
          cookieText += "; path=" + path;
        }
        if (domain) {
          cookieText += "; domain=" + domain;
        }
        if (secure) {
          cookieText += "; secure";
        }
      } else {
        cookieText += "; expires=" + Date(0).toGMTString();
      }
      document.cookie = cookieText;
    },
    /**  Settings 1 A cop cookie
    *  param name :  Denote cookie Name of, required 
    *  param subName :  Representator cookie Name of, required 
    *  param value :  Representator cookie Value of, required 
    *  param expires :  Denote cookie You can not fill in the expiration time of 
    *  param domain :  Denote cookie The domain name of, you can not fill in 
    *  param path :  Denote cookie You can not fill in the path of 
    *  param secure :  Denote cookie Safety sign of, may not fill in 
    *  eg : SubCookieUtil.set("info", "sex", "boy");
    **/
    set : function (name, subName, value, expires, domain, path, secure) {
      var cookies = this.getAll(name) || {};
      cookies[subName] = value;
      this.setAll(name, cookies, expires, domain, path, secure);
    },
    /**  Read 1 Strip integrity cookie
    *  param name :  Denote cookie Name of, required 
    *  return : 1 A cookie Object 
    *  eg : SubCookieUtil.getAll("info");
    **/
    getAll : function (name) {
      var cookieName = encodeURIComponent(name) + "=",
        cookieStart = document.cookie.indexOf(cookieName),
        cookieValue = "", i, len, subCookies, parts, result = {};
      if (cookieStart > -1) {
        var cookieEnd = document.cookie.indexOf (";", cookieStart);
        if (cookieEnd == -1) {
          cookieEnd = document.cookie.length;
        }
        cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
        if (cookieValue.length > 0) {
          subCookies = cookieValue.split("&");
          for (i = 0, len = subCookies.length; i < len; i++) {
            parts = subCookies[i].split("=");
            result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
          }
          return result;
        }
      }
      return null;
    },
    /**  Get 1 A cop cookie Value of 
    *  param name :  Denote cookie Name of, required 
    *  param subName :  Representator cookie Name of 
    *  return : 1 Sub cookie Value of 
    *  eg : SubCookieUtil.get("info", "name");
    **/
    get : function (name, subName) {
      var cookies = this.getAll(name);
      if (cookies) {
        return cookies[subName];
      } else {
        return null;
      }
    }, 
    /**  Delete 1 Strip integrity cookie
    *  param name :  Denote cookie Name of, required 
    *  param domain :  Denote cookie The domain name of, you can not fill in 
    *  param path :  Denote cookie You can not fill in the path of 
    *  param secure :  Denote cookie Safety sign of, may not fill in 
    *  eg : SubCookieUtil.unsetAll("info");
    **/
    unsetAll : function (name, domain, path, secure) {
      this.setAll(name, "", Date(0).toGMTString(), domain, path, secure);
    },
    /**  Delete 1 A cop cookie
    *  param name :  Denote cookie Name of, required 
    *  param subName :  Representator cookie Name of, required 
    *  param domain :  Denote cookie The domain name of, you can not fill in 
    *  param path :  Denote cookie You can not fill in the path of 
    *  param secure :  Denote cookie Safety sign of, may not fill in 
    *  eg : SubCookieUtil.unset("info", "name");
    **/
    unset : function (name, subName, domain, path, secure) {
      var cookies = this.getAll(name);
      if (cookies) {
        delete cookies[subName];
        this.setAll(name, cookies, null, domain, path, secure);
      }
    }  
  };
  //  Test: 
  var zhang = {
    name : "zhang",
    age : 23,
    height : "178cm",
    weight : "66kg"
  }
  //  Settings 1 Complete cookie
  SubCookieUtil.setAll("zhang", zhang);
  //  Get 1 Complete cookie
  var zhang = SubCookieUtil.getAll("zhang");
  alert(zhang.weight);  // 66kg
  //  Add it for Zhang again 1 Sub cookie
  SubCookieUtil.set("zhang", "sport", "basketball");
  //  Acquirer cookie
  alert(SubCookieUtil.get("zhang", "sport")); // basketball
  //  Delete 1 A cop cookie
  SubCookieUtil.unset("zhang", "age");
  alert(SubCookieUtil.get("zhang", "age"));  // undefined
  //  Delete 1 Complete cookie
  SubCookieUtil.unsetAll("zhang");
  alert(SubCookieUtil.getAll("zhang"));  //  Error reported because it has been deleted 

The above is the whole content of this paper, hoping to help everyone's study.


Related articles: