Cookies and Web Storage

Source: Internet
Author: User
Tags http cookie set cookie setcookie browser cache ssl connection sessionstorage

First, Cookie1. HTTP Headers and Cookies

A cookie is a short name for an HTTP cookie. This standard requires:

(1) The HTTP response header of the server contains the Set-cookie field

Response head Eg:

HTTP/1.1 200 OKContent-Type: text/htmlSet-Cookie: name=value

The HTTP response is set with a cookie named name and a value of values. The server sends them to the browser, and the browser stores such cookie information.

(2) The browser's HTTP request header contains a cookie field

Request Head eg:

GET /index.html HTTP/1.1Cookie: name=value

The browser adds a cookie field for each request header and sends the cookie information that the browser contains locally back to the server.

2. Characteristics of a cookie (1) A cookie is bound to a specific domain name

When a cookie is set under a domain name, the cookie is sent when a request is sent to that domain name.

(2) The number and size of cookies under a single domain limit the number of cookies:
    • ie7+: Maximum of 50
    • Firefox: Maximum of 50
    • Opera: Maximum of 30
    • Chrome and Safari: Unlimited

After the cookie exceeds the limit, the browser clears the previously set cookie. The specific deletion method is different for different browsers.

Cookie size Limits

The total length of all cookies under a single domain in most browsers is limited to around 4096B . For browser compatibility It is best to limit it to <= 4095B

(3) If no expiry time is set, the cookie will be deleted when the browser is closed 4. API:document.cookie (1) Get cookies
var allCookies = document.cookie;//name1=value1;name2=value2;name3=value3

You can get all the cookies available on the current page, separated by semicolons for each cookie. after obtaining a cookie key value pair, you need to use decodeURIComponent () to decode each cookie name and cookie value

(2) Setting cookies
document.cookie = encodeURIComponent(name)+ ‘=‘ + encodeURIComponent(value) + ‘;path=somepath;domain=somedomain;max-age=somemaxage;expires=someexpires;secure‘;
    • Use the above method to set a new cookie string. This cookie string is interpreted and added to the existing collection of cookies. The does not overwrite existing cookies .

    • Only name and value are required. It is best to use encodeURIComponent () to encode name and value when set:

    • Has the following optional cookie properties that can be followed by a name value pair:

      • domain=: Specifies which domain the cookie is valid for, all pages under that domain can access the cookie, and all requests sent to that domain will be sent to that cookie. Default domain for setting cookies

      • Path=: Specifies which path the cookie is valid for. such as '/mydir ', you can specify that the cookie is accessible only from the '/mydir ' path under the specified domain name. The other path and root directory under the domain cannot access the cookie , nor does it send the cookie to the server. path to the default current document location

      • Max-age=: Specifies the time, in S, for the cookie to be valid. Normal, max-age priority is higher than expires

      • Expires=: Specifies the cookie expiration time, in GMT format. such as: (New Date ()). toUTCString ()

      • Secure: Security flag, when specified, cookies can only be sent to the server when the SSL connection (HTTPS protocol) is used.

Note: These properties are only present in the browser and are not sent to the server as part of the cookie information, sending only name value pairs, that is, the cookie field in the request header contains only the name value pairs , but these properties are sent from the server to the browser, Used to indicate to the browser that the set-cookie field in the S response header contains not only name-value pairs, but also these cookie attributes

5. The framework for customizing the Cookie method MDN:
/*|*|  * 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.replac E (New RegExp ("?:(?: ^|. *;) \\s* "+ encodeuricomponent (SKey). Replace (/[\-\.\+\*]/g," \\$& ") +" \\s*\\=\\s* "([^;] *). *$) |^.*$ ")," $ ")) | |  Null }, Setitem:function (SKey, svalue, Vend, spath, Sdomain, bsecure) {if (!skey | |/^ (?: Expires|max\-age|path|domain|se    Cure) $/i.test (SKey)) {return false;}    var sexpires = ""; if (vend) {switch (vend.constructor) {case Number:sexpires = Vend = = = Infinity? "; Expires=fri, 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, 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:/* 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; }};
The framework of the JavaScript Advanced programming:
Const COOKIEUTIL = {get:function (name) {Const COOKIENAME = encodeuricomponent (name) + ' = ';    Const Cookiestart = document.cookie.indexOf (cookiename);      if (cookiestart >= 0) {Let cookieend = document.cookie.indexOf ('; ', Cookiestart);      if (cookieend = = =-1) {cookieend = Document.cookie.length;      } Const Cookievalue = decodeURIComponent (document.cookie.subString (Cookiestart + cookiename.length, cookieend));    Return Cookievalue} else {return null; }}, Set:function (name, value, expires, path, domain, secure) {Const COOKIETEXT = encodeuricomponent (name) + ' = ' +    encodeURIComponent (value);    if (expires instanceof Date) {cookietext + = '; expires=${expires.toutcstring ()} ';    } if (path) {cookietext + = '; Path=${path} ';    } if (domain) {cookietext + = '; Domain=${domain} ';  if (secure) {cookietext + = '; secure '} document.cookie = Cookietext; }, Unset:function (name, path, domain, secure) {This.set (name, "', New Date (0), domain, Secure)}} 
FTC Framework
function GetCookie (name) {Const COOKIESTR = Document.cookie;  Const Namelen = name.length;  Const NAMESTARTINDEX = cookiestr.indexof (name+ ' = ');  if (Namestartindex < 0) {return null;  } Const VALUESTARTINDEX = namestartindex + Namelen + 1;  Let Valueendindex = Cookiestr.indexof ('; ', valuestartindex); if (!valuestartindex && name!== cookiestr.substring (0, Namelen)) {////When startindex is 0 indicates that name is the first cookie,  That name must be cookiestr.substring (0, name.length) return null;    } if (Valueendindex = = = 1) {//indicates that it is the last cookie, followed by No;  Valueendindex = Cookiestr.length; } return decodeURIComponent (Cookiestr.substring (Valuestartindex, Valueendindex));} function Setcookie (name, value, sec, path, domain) {var argv = setcookie.arguments, argc = setcookie.argument S.length, expires = new Date (), secure = (argc > 5)?  ARGV[5]: false; Path = (argc > 3)?  ARGV[3]: null; Domain = (argc > 4)? ARGV[4]: null; if (sec = = = NULL | | sec = = = ") {sec = 600 * (24 * 60 * 60 * 1000);}  else {sec = 1000*sec;}  Expires.settime (Expires.gettime () + sec); Document.cookie = name + ' = ' + escape (value) + ((expires = = = NULL)? ": ('; expires= ' + expires.togmtstring ())) + (Path = = = null)? '/': ('; path= ' + path) + ((domain = = = null)? ': ('; domain= ' + domain) ' + ((secure = = = True)? ‘;  Secure ': ');  }function Deletecookie (name) {var exp = new Date (), cval = GetCookie (name);  Exp.settime (Exp.gettime ()-1); Document.cookie = name + ' = ' + Cval + '; Expires= ' + exp.togmtstring ();}
6. * Sub-Cookie has meaning

To circumvent the limit on the number of cookies under the browser's single domain name . Cookies can be stored and accessed using a single cookie, rather than using a different cookie store for each name value pair.

The most common format for child cookies:

name=name1=value1&name2=value2&name3=value3
How to obtain the child cookie information:
Const SUBCOOKIEUTIL = {get:function (name, subname) {Const Subcookies = This.getall (name);    if (subcookies) {return subcookies[subname];    } else {return null;    }}, Getall:function (name, subname) {Const COOKIENAME = name + ' = ';    Const Cookiestart = document.cookie.indexOf (cookiename);    Let Subcookievaluestr;      if (cookiestart >= 0) {var cookieend = document.cookie.indexOf ('; ', Cookiestart);      if (Cookieend <0) {cookieend = Document.cookie.length;      } subcookievaluestr = document.cookie.subString (Cookiestart + cookiename.length, cookieend);        if (Subcookievaluestr.length > 0) {subcookieitemarr = Subcookievaluestr.split (' & ');        Const result = {};          For (Let item of Subcookieitemarr) {Const KEYVALUEARR = item.split (' = ');          if (keyvaluearr.length = = 2) {result[decodeuricomponent (keyvaluearr[0])] = decodeURIComponent (keyvaluearr[1]); }} return ResUlt    } return null;  } return null; }}
Ii. Introduction to Web storage:sessionstorage and Localstorage1.web Storage

The Web storage includes sessionstorage, globalstorage,localstorage three kinds.

Characteristics

Overcomes some of the limitations of cookies:

    • WEB storage stored data is tightly controlled on the client side and does not send data back to the server
    • Greater data storage capacity. For Localstorage, most browsers limit 5MB for each source, and also 2.5MB. Sessionstorage Some limitations are 2.5MB, some 5MB.

There are three different types of features.

API methods:

Three storage instances have the following methods:

    • Storage.getitem (name): Gets the value corresponding to the specified name
    • Storage.key (Index): Gets the name of the name value pair at the index position
    • Storage.removeitem (name): Deletes the name value specified by name
    • Storage.setitem (name, value): Sets a value for the specified name

Each name value pair is stored as an attribute on the storage object, so you can also pass '. ' or ' [] ' to access the property to get the value, delete the object property through the delete. However, it is more recommended to use methods to access data.

Event

Storage event.

Any modifications to the storage object will trigger the storage event. Includes adding, modifying, and deleting data.

Its event object properties:

    • Domain
    • Key: Set or delete the keys name
    • NewValue: The new value if the value is set, or null if the value is deleted
    • OldValue: Change the previous value
2. Introduction to Sessionstorage Objects

The Sessionstorage object stores data specific to a session (page) and is specific to a particular session 's understanding:

    • A conversation is the meaning of a page . The data can only be accessed by the page that originally stored the data for the object. It is not accessible by other pages.
    • A page session remains in the browser while it is open, and reloading or resuming the page still maintains the original page session . opening a page in a new tab or a new window initializes a new session .
    • The data is purged when the page session ends (that is, when the browser is closed ).
Case:
sessionStorage.setItem(‘name‘,‘Boonie‘);sessionStorage.getItem(‘name‘);//"Boonie"sessionStorage.removeItem(‘name‘);const data = {};for(let i=0, len = sessionStorage.length; i<len; i++) {  const name = sessionStorage.key(i);  const value = sessionStorage.getItem(name);  data[name] = value;}
3. Introduction to Localstorage Objects

The Localstorage object stores data that is specific to a domain name , across conversations , and persisted . Specific understanding:

    • Access to the same Localstorage object, the page must conform to the same Origin protocol (i.e. the domain name, protocol, and Port)
    • Can be accessed across conversations (pages) as long as the page conforms to the same-origin protocol
    • If you do not use RemoveItem () or delete delete and do not clear the browser cache , the data stored in Localstorage will persist and remain on disk.
Case
localStorage.setItem(‘name‘, ‘Bonnie‘);localStorage.getItem(‘name‘);
4. Introduction to *globalstorage[' xxx.com ' objects

Localstorage replaced the globalstorage.

Features and Localstorage are basically the same, but compared to Localstorage, Globalstorage has specific access restrictions: You need to specify the domain by []. the Globalstorage object is not an storage instance, globalstorage[' xxx.com ' is the storage instance.

Localstorage equivalent to Globalstorage[location.host]

Most browsers do not support globalstorage,chrome or support.

Tips:location.host contains the domain name and port number, Location.hostname is only the domain name, Location.port is just the port number.

Case
globalStorage[‘www.example.com‘].getItem(‘name‘);
Resources

Https://developer.mozilla.org/zh-CN/docs/Web/API/Document/cookie
Https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
JavaScript Advanced Program Design (CHAPTER23)

Cookies and Web Storage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.