The use of JS Cookie detailed introduction

Source: Internet
Author: User
Tags current time getdate parent directory set cookie setcookie

Cookies are based on the HTTP protocol, cookies are restricted storage strings, we can store strings by Document.cookie.

And a recent project on hand involves the operation of cookies, that is, login and exit,

The logic is simple for this requirement.

1. Pre-logon cookie Check

2. Login back-end data and save to cookie

3. Log out and clear cookies.

In addition to logic, this involves the issue of cookie values and values.

Here I use jquery's Third-party plugin $.cookie to get values and settings.

Based on the logic above and $.cookie to value and set the value, the task is quickly completed, the local Apache test is not a problem.

Then submitted to the test, not surprisingly the problem immediately appeared, the current site is a.xxx.com, and our other two-level domain name of the site b.xxx.com also have logins, that is, two sites can be set document.domain= "xxx.com"

After the site b.xxx.com login successfully, has written a $.cookie ("userid"), in the console dozen document.cookie= "userid=112343",

The first time into the a.xxx.com seems to be right, because $.cookie ("userid") has a value, so it will also enter the logged in state, but the point of exit login,

Enter the b.xxx.com again after the login state. Is the cookie not shared, look down document.cookie= "userid=112343;userid=0";

It's strange here that when A.xxx.com exits, the $.cookie ("userid", 0) has been set, but it does not overwrite the previous userid, but instead appends a new userid=0, before the UserID still exists.

It seems that cleaning cookies is not as simple as setting the value.

Check the information on the Internet, that is, the elimination of cookies also need to increase the expiration time, that is, less than the current time on it, the code will be modified into

$.cookie ("userid", 0, {expirs:new Date ()-1000});

But it's still not working.

Here also popular science under the composition of cookies, cookies are actually made up of Name,value, Expires,path,domain and other attributes,

If you set path and domain when you write cookies, you also need to set the same path,domain when you clear cookies, or if domain is not set, take the current location.host

So the reason has been found.

When B.xxx.com wrote the cookie set domain:xxx.com, and path: '/', while I a.xxx.com the cookie only set the value and expiration time, and did not write domain and path, so and

Did not clear the original userid, but generated a new userid, this userid Default domain for a.xxx.com, just because there is expiration time, immediately eliminated. But did not clear the previous userid.

So change the code to

$.cookie ("userid", 0,{expires:new Date () -1000, domain: "7k7k.com", Path: "/"}

That is, clear the previous userid.
Two. read operation of Cookies

The exact way to read a cookie is simply to manipulate the string. Copy this code from the W3school to do the analysis:

function GetCookie (c_name) {
if (document.cookie.length>0) {///First query whether the cookie is empty, return ""
C_start=document.cookie.indexof (c_name + "=")//through the String object's IndexOf () to check whether the cookie exists, does not exist 1
if (c_start!=-1) {
C_start=c_start + c_name.length+1//finally this +1 actually means "=", so you get the starting position of the cookie value
C_end=document.cookie.indexof (";", C_start)//In fact, I just saw IndexOf () the second parameter when suddenly a bit dizzy, then remembered to indicate the location of the specified start index ... This sentence is to get the end position of the value. Because of the need to consider whether the last one, so through the ";" Whether the number exists to judge
if (c_end==-1) c_end=document.cookie.length
Return unescape (document.cookie.substring (c_start,c_end))//Gets the value through substring (). To understand Unescape () is to know what escape () is to do, are very important basis, want to understand the search can be, at the end of the article will also explain the cookie coding details
}
}
Return ""
}

Of course, there are a number of ways to read cookies, such as arrays, and so on, here is not to elaborate.

Three. Set the expiration date of the cookie

The life cycle of the cookie that often appears in the article is the period of validity and expiration, that is, the existence time of the cookie. By default, cookies are automatically cleared when the browser is closed, but we can set the expiration date of the cookie by expires. The syntax is as follows:

Document.cookie = "Name=value;expires=date"

The date-type string in the preceding code, in GMT (GMT) format, is generated as follows:

var _date = new Date ();
_date.setdate (_date.getdate () +30);
_date.togmtstring ();

The above three lines of code are broken down into several steps:

Generate a date instance through new to get the current time;

The GetDate () method gets the day of the current local month, plus 30 is what I want the cookie to be stored locally for 30 days;

Then the Setdate () method is used to set the time;

Finally, the date object is converted to a string using the toGMTString () method, and the result is returned

Here's a complete function to illustrate what we need to be aware of in creating cookies-copied from W3school. To create a function that stores information in a cookie:

function Setcookie (c_name, value, Expiredays) {
var exdate=new Date ();
Exdate.setdate (exdate.getdate () + expiredays);
Document.cookie=c_name+ "=" + Escape (value) + ((expiredays==null)? "": "; expires=" +exdate.togmtstring ());
}
How to use: Setcookie (' username ', ' Darren ', 30)

Now our function is to set the valid time of the cookie according to the number of days, if you want to set it in other units (such as: hours), then change the third line of code:

Exdate.sethours (exdate.gethours () + expiredays);

After this setting, the cookie validity period is in hours.

There are two ways to get rid of cookies in common problems, but now it's time to disable the cookie by setting the expiration date to an expired time. Now that there is a way to set the expiration date, then the method of setting the expiration period invites interested friends to do their own ^_^. Below continue the deeper cookie topic.


Cookie Advanced Article


A. Cookie path concept

In the basics, there is a reference to the notion that a cookie has a domain and a path, now to describe the path's role in the cookie.

Cookies are typically created by the user accessing the page, but not only on the page where the cookie is created.

By default, only pages that are in the same directory or subdirectory as the page in which the cookie was created are accessible because of security considerations that do not allow all pages to freely access cookies created by other pages. As an example:

So how to get this cookie to be accessed by other directory or parent directory Access class, by setting the path of the cookie can be implemented. Examples are as follows:

Document.cookie = "Name=value;path=path" Document.cookie = "Name=value;expires=date;path=path" The Red font path is the way of the cookie, the most A common example is to have cookies in the directory, so that no matter which child pages create cookies, all pages can be accessed:

The code is as follows Copy Code
Document.cookie = "name=darren;path=/"

Two. cookie Domain concept

The path solves the problem of accessing cookies under the same domain, and we go on to say that cookies implement the problem of accessing the same domain. The syntax is as follows:

  

The code is as follows Copy Code
Document.cookie = "Name=value;path=path;domain=domain"

The red domain is the value of the cookie field set.

For example, "www.qq.com" and "sports.qq.com" common an associated domain name "qq.com", if we want to "sports.qq.com" cookies under "www.qq.com" access, we need to use cookies Domain attribute, and you need to set the Path property to "/". Cases:

The code is as follows Copy Code
Document.cookie = "username=darren;path=/;d omain=qq.com"

Note: A certain is the access between the same domain, you can not set the value of domain to the domain name of the non-primary domain.

Three. Cookie Security

Cookie information is usually used to pass data using an HTTP connection, which can be easily viewed, so cookies store information that is easily stolen. If the content passed in the cookie is more important, then the encrypted data transfer is required.

So the name of this property for the cookie is "secure," and the default value is null. If the property of a cookie is secure, it communicates data between the server via HTTPS or another security protocol. The syntax is as follows:

Document.cookie = "Username=darren;secure" Sets the cookie to secure, only to ensure that the data transfer process between the cookie and the server is encrypted, while the locally stored cookie file is not encrypted. If you want to encrypt the local cookie, you have to encrypt the data yourself.

Note: Even if the secure attribute is set, it does not mean that others cannot see the cookie information that is stored locally on your machine, so in the final analysis, don't put the important information on the cookie,??..

Four. Cookie coding details

Originally wanted to introduce the cookie code knowledge in the FAQ section, because if you don't know the coding problem is really a pit, so say it in detail.

When you enter cookie information, you cannot include spaces, semicolons, commas, and other special symbols, and in general, the storage of cookie information is in a way that is not encoded. So, before setting cookie information, use the escape () function to encode the cookie value information, and then use the unescape () function to convert the value back when the cookie is worth the time. When setting cookies:

The code is as follows Copy Code
Document.cookie = name + "=" + Escape (value)

Take a look at the phrase in GetCookie () mentioned in the basic usage:

The code is as follows Copy Code
Return unescape (document.cookie.substring (c_start,c_end))

This doesn't have to worry because there is a special symbol in the cookie value that causes the cookie information to go wrong.

Instance

The code is as follows Copy Code

<script>

//write cookies function Author: Zhangkai
function Setcookie (name,value)///two parameters, one is the name of the cookie, one is the value
{
    var days = 30; This cookie will be saved for 30 days
    var exp  = new Date ();   //new Date ("December 31, 9998");
    Exp.settime (exp.gettime () + days*24*60*60*1000);
    document.cookie = name + "=" + Escape (value) + "; expires=" + exp.togmtstring ();
}
Function GetCookie (name)//cookies functions        
{
     var arr = Document.cookie.match (New RegExp ("(^|)" +name+ "= ([^;] *)(;|$)"));
     if (arr!= null) return unescape (arr[2), return null;

}
function Delcookie (name)//Delete cookie
{
var exp = new Date ();
Exp.settime (Exp.gettime ()-1);
var cval=getcookie (name);
if (cval!=null) document.cookie= name + "=" +cval+ "; expires=" +exp.togmtstring ();
}

Setcookie ("Xiaoqi", "3")
Alert (GetCookie (' Xiaoqi '));
</script>

A very useful JavaScript read-write cookie function

A very useful JavaScript read-write cookie function

The code is as follows Copy Code

function Getcookieval (offset)
Get the value of the cookie after decoding
{
var endstr = documents.cookie.indexOf (";", offset);
if (endstr = = 1)
Endstr = Documents.cookie.length;
Return unescape (documents.cookie.substring (offset, endstr));
}
function Setcookie (name, value)
Set cookie Value
{
var expdate = new Date ();
var argv = setcookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2)? ARGV[2]: null;
var path = (argc > 3)? ARGV[3]: null;
var domain = (argc > 4)? ARGV[4]: null;
var secure = (argc > 5)? ARGV[5]: false;
if (expires!=null) Expdate.settime (Expdate.gettime () + (expires * 1000));
Documents.cookie = name + "=" + Escape (value) + ((expires = null)?  ""  :  ("; Expires= "+ expdate.togmtstring ()))
+ ((path = null)?  ""  :  (";  Path= "+ path") + ((domain = null)?  ""  :  ("; domain= "+ domain)"
+ (Secure = = True)?  "; Secure ":" ");
}
function Delcookie (name)
Delete Cookies
{
var exp = new Date ();
Exp.settime (Exp.gettime ()-1);
var cval = GetCookie (name);
Documents.cookie = name + "=" + Cval + "; Expires= "+ exp.togmtstring ();
}
function GetCookie (name)
Get the original value of the cookie
{
var arg = name + "=";
var alen = Arg.length;
var clen = documents.cookie.length;
var i = 0;
while (I < Clen)
{
var j = i + Alen;
if (Documents.cookie.substring (i, j) = arg)
Return Getcookieval (j);
i = Documents.cookie.indexOf ("", I) + 1;
if (i = = 0) break;
}
return null;
}

<script language= "JavaScript" >
<!--
function Openpopup () {
Url= "Popup.htm"
window.open ("gonggao.htm", "Gonggao", "Width=260,height=212,left=200,top=0")
}

function Get_cookie (Name) {
var search = Name + "="
var returnvalue = "";
if (Documents.cookie.length > 0) {
offset = documents.cookie.indexOf (search)
if (offset!=-1) {
Offset + = Search.length
End = Documents.cookie.indexOf (";", offset);
if (end = = 1)
end = Documents.cookie.length;
Returnvalue=unescape (documents.cookie.substring (offset, end))
}
}
Return returnvalue;
}

function Helpor_net () {
if (Get_cookie (' popped ') = = ") {
Openpopup ()
Documents.cookie= "Popped=yes"
}
}
Helpor_net ()
-->
</SCRIPT>

If the point is OK, as long as the cookie is not clear, later access will not be prompted, if not the point of determination will be prompted each time. In the JS file, the whole station contains

The code is as follows Copy Code

<script language= "JavaScript" >
<!--
var the_cookie = Document.cookie;
var Broken_cookie = The_cookie.split (":");
var the_visiteraccepted = unescape (broken_cookie[1]);
//
if (the_visiteraccepted== "undefined") {
var tmp=confirm (' When and where ' Chinese people. ');
if (Tmp==false) {
Window.close ();
}else{
var the_visiteraccepted = 1;
var The_cookie = "ilovechina=visiteraccepted:" + Escape (the_visiteraccepted);
Document.cookie = The_cookie;
}
}
-->
</SCRIPT>


Summarize:

1.cookie is not a simple name and value two attributes, there are attributes such as Expires,domain,path, this can be used specifically to find the concept of cookies familiar.

2. The cookie must be in accordance with domain and path when the cookie is set. Otherwise it will not be cleared but appended.

Cookies should have many other aspects of the problem, I hope you can help the author to add.

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.