JavaScript operation Cookie Instance code sharing

Source: Internet
Author: User

Compared to JavaScript, it is easier to manipulate cookies through back-end PHP. So because the previous very rarely through JS to manipulate cookies, in the use of JavaScript to manipulate cookies encountered some detours, but also to share out, so that everyone and I make the same mistake.

1th, I know that Document.cookie returns a string of all cookies, so when setting cookies, I take it for granted that the new cookie is spliced onto the string and then assigned to Document.cookie.

After testing, completely not so, document.cookie= ""; is to add or update new cookies, such as document.cookie= "Myck=yes;" A cookie with the name Myck is added, and if you want to add multiple cookie,document.cookie= "key1=1;key2=2;" If you want to add expiration time, storage domain and other information, directly followed by the relevant parameters. For example: Document.cookie= ' Myck=yes; Expires=expire_time;domain=domain '.

This operation does not affect an existing cookie that is not the same name.

2nd, set the expiration time of the cookie, I mistakenly thought it was set a timestamp on the line, the results measured, found no effect, cookie Lifetime is always the session cycle. Later found to use the standard string time format, similar to "Mon June 20:08:10 gmt+0800 GMT." If you use 1343045321299 this, it is invalid.


Cookie.js file

The code is as follows Copy Code

var cookie= (function () {

var getdatestring=function (offset) {

var date=new date ();

Date.settime (+date+offset*1000);

return date.togmtstring ();

},

Getcookies=function () {

var cookie=document.cookie| | ',

Subs=cookie.split (/;s?/),

_subs,cks={};

for (Var i=0;i<subs.length,subs[i];i++) {

_subs=subs[i].split (' = ')

Cks[unescape (_subs[0])]=unescape (_subs.slice (1). Join (' = '));

}

return cks;

}


return {

Refresh:function () {

This.cookies=getcookies ();

return this;

},

Has:function (key) {

return this.cookies[key]!=null;

},

Get:function (key) {

return This.cookies[key];

},

Set:function (key,value,expire,path,domain,secure) {

var myck=escape (key) + ' = ' +escape (value==null? ': value);

if (!isnan (expire=parsefloat (expire))

myck+= '; expires= ' +getdatestring (expire);

if (path) myck+= ';p ath= ' +path;

if (domain&&domain!=location.hostname) myck+= ';d omain= ' +domain;

if (secure) myck+= '; secure ';

Document.cookie=myck;

Return This.refresh (). has (key);

},

Remove:function (Key,path,domain) {

var paths=[],

Domains=[],

Arr,self=this;

if (path) {

Paths=[path];

}else{

Arr=location.pathname.match (/.*?/|. +$/G);

This.each (Arr,function (i) {

var A;

Paths.push (A=arr.slice (0,i+1). Join (")");

if (/[^/]+/$/.test (a)) {

Paths.push (A.slice (0,-1));

}

if (/[^/]$/.test (a)) {

Paths.push (A + '/');

}

});

}


if (domain) {

Domains=[domain];

}else{

Arr=location.hostname.split ('. ');

This.each (Arr,function (i) {

Domains.push (Arr.slice (-i). Join ('. '));

});

Domains.push ('. ') +domains[0]);

}


This.each (Paths,function () {

var path=this+ ';

Self.each (Domains,function () {

Self.set (Key, ', -1000,path,this+ ');

});

});


Return!! path| |!! domain| |! This.has (key);

},

Clear:function (Path,domain) {

for (var key in this.cookies) {

This.remove (Key,path,domain);

}

Return!! path| |!! domain| | function () {

for (var key in this.cookies) {

return false;

}

return true;

}.call (this);

},

Each:function (Arr,func) {

var i=0,j=arr.length;

for (; i<j;i++) {

if (Func.call (arr[i],i) ===false) {

Break

}

}

}

}.refresh ();

})();

First, introduce cookie.js into the page

The code is as follows Copy Code

Call
Cookie.has (name); Detect if there is a cookie named name
Cookie.set (Key,value,expire,path,domain); Set a new cookie,true indicates that the setting was successful, false indicates that the setting failed
Cookie.remove (Name,path,domain); Deleting cookie,true named name indicates successful deletion, False indicates deletion failed
Cookie.get (name); Gets the value of a cookie named name
Cookie.clear (Path,domain); Clear All Cookies

Note: The Remove and clear methods, if you do not set path or domain, will delete all the root domains, subdomains, cookies under each depth path.

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.