I. Grammar
1.1 Get all cookies for the current page:
var allcookies = Document.cookie;
Allcookies is a string that contains a semicolon-delimited list of cookie strings (that is, key=value key-value pairs).
1.2 Write a new cookie:
Document.cookie = Updatedcookie;
Updatedcookie is a string that is a key-value pair form. You can only use this method to set or update one cookie at a time, and the write is not overwritten, but added. For example:
Document.cookie = "fontsize=14";
Document.cookie = "fontsize=16";
Document.cookie = "Fontcolor=black";
Document.cookie; Fontsize=16;fontcolor=black
1.3 Optional Properties:
In addition to the contents of the cookie itself, there are some optional properties that can be written to define the cookie set/update, followed by a semicolon to separate:
set-cookie:value[; expires=date][; domain=domain][; path=path][; secure]
(1) Path=path (for example '/', '/mydir ') if there is no definition, the path of the current document location is implied.
(2) Domain=domain (e.g. ' example.com ', '. example.com ' (including all subdomains), ' subdomain.example.com ') if there is no definition, the domain name portion of the path that defaults to the current document location.
(3) Max-age=max-age-in-seconds (for example, one year for 606024*365)
(4) Expires=date-in-gmtstring-format if not defined, the cookie expires at the end of the conversation. The format of this value is see date.toutcstring ().
(5) Secure (cookies are transmitted only via HTTPS protocol) the value string of a cookie can be encodeuricomponent () to ensure that it does not contain any commas, semicolons, or spaces (the values are not allowed in cookie values).
Two. Cookie interface encapsulation:
var cookieutil = {//Set cookie Setitem:function (name, value, days) {var date=new date ();
Date.setdate (Date.getdate () +days);
document.cookie=name+ ' = ' +value+ '; expires= ' +date;
//Get the cookie getitem:function (name) {var arr=document.cookie.replace (/\s/g, ""). Split (';');
for (Var i=0;i<arr.length;i++) {var temparr=arr[i].split (' = ');
if (temparr[0]==name) {return decodeuricomponent (temparr[1]);
} return ';
},//delete cookie Removeitem:function (name) {This.setitem (name, ' 1 ',-1); //Check to see if a cookie hasitem:function (name) {return RegExp (?: ^|;\
\s*) "+ encodeuricomponent (name). replace (/[\-\.\+\*]/g," \\$& ") +" \\s*\\= "). Test (Document.cookie); //Get all the cookie list getallitems:function () {var Cookiearr = Document.cookie.replace (/(?: ^| \s*;) [^\=]+] (? =;|$) |^\s*|\s* (?: \ =[^;] *)? (?:\ 1|$)/g, ""). Split (/\s* (?: \ =[^;] *)?;\
s*/); for (var nidx = 0; nidx < cookiearr.length;nidx++) {Cookiearr[nidx] = decodeURIComponent (Cookiearr[nidx]);}
return Cookiearr; }
};
Summarize
The above is JavaScript cookie tool function encapsulation All content, hope this article content to everybody's study or work can bring certain help, if have the question everybody can message exchange.