JavaScript Learning Note--cookie

Source: Internet
Author: User
Tags set cookie setcookie

What is a Cookie

"A cookie is a variable stored on a visitor's computer. This cookie is sent whenever a page is requested by the same computer through a browser. You can use JavaScript to create and retrieve the value of a cookie. "-W3school
A cookie is a file created by a visited website that stores browsing information, such as profile information.

From the JavaScript point of view, a cookie is a string of information. This information is stored on the client computer and is used to pass information between the client computer and the server.
This information can be read or set through Document.cookie in JavaScript. Because cookies are used to communicate between the client and the server, the server language (such as PHP) can access cookies in addition to JavaScript.

Basic Cookie Knowledge

    • There are two types of cookies:
      • Cookies that you browse to the current website itself set
      • Third-party cookies from other domain sources, such as embedding ads or images on a Web page (websites may use these cookies to track your usage information)
    • In the basic knowledge there is a question about the cookie life cycle, in fact, the cookie can be broadly divided into two states:
      • A cookie of a temporary nature. The website will store some of your personal information during the current use, and the information will be removed from the computer when the browser is closed.
      • Set the cookie for the expiration time. Even if the browser is turned off, the information industry will still be in the computer. such as a login name and password, so that you do not have to log in every time you go to a specific site. This cookie can be kept in a computer for days, months or even years
    • There are two ways to clear a cookie:
      • Use browser tools to clear cookies (with third-party tools, which are also available in the browser itself)
      • To clear cookies by setting the period of validity of the cookie
      • Note: Deleting cookies can sometimes cause some pages to not function properly
    • Browsers can accept and deny access to cookies through settings.
    • For functional and performance reasons, it is recommended to minimize the number of cookies used and to use small cookies as much as possible.
    • Details of the cookie code will be presented separately in the cookie Premium section.

Cookie Basics Usage

A. Simple access operation

The cookie property of the Document object must be used when accessing cookies using JavaScript, and a line of code describes how to create and modify a cookie:

Document.cookie  = ' Username=darren '

In the above code ' username ' denotes the cookie name, ' Darren ' indicates the value corresponding to the name. Assuming that the cookie name does not exist, create a new cookie;

Two. Cookie method

//Set Cookies    functionSetcookie (Name,value,day) {//Cookie: Name, value, expiration time        varDate=NewDate (); Date.setdate (Date.getdate ()+Day ); //document.cookie=name+ "=" +value+ "; expires=" +date;Document.cookie=name+ "=" + Value + ((day==NULL) ? "": "; expires=" +date); }    //Get Cookies    functionGetCookie (name) {//The cookie is stored as a string: Username=haha; password=123; sex=man; age=29        varArr=document.cookie.split (";"); //split Group [Username=haha, password=123,sex=man,age=29]         for(vari=0;i<arr.length;i++){            varArr2=arr[i].split ("="); //[Username,haha]            if(arr2[0]==name) {                returnArr2[1]            }        }        return""; }    //Delete Cookies    functionRemovecookie (name) {Setcookie (name,"1",-1); } Setcookie ("UserName", "haha", 7); Setcookie ("PassWord", "123", 1); Setcookie ("Sex", "man", 1); Setcookie ("Age", "29", 1); Setcookie ("Test", "29", 1); Setcookie ("Test2", "30"); Alert (GetCookie ("UserName")) Removecookie ("UserName") alert (document.cookie)

Now the function is to set the effective time of the cookie by the number of days, and if you want to set it in a different unit (for example: hours), change the third line of code:

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

In this way, the expiration date of the cookie is set in hours.

Cookie Premium Article

I. Cookie path concept

In the basics, there is a reference to the concept of a cookie with a domain and a path, and now it describes the role of the path in the cookie.

Cookies are generally created as a result of a user's access to a page, but this cookie is not accessible only on the page where the cookie was created.

By default, only pages that are in the same directory or subdirectory as the page where the cookie was created are accessible, because of security considerations, which makes it not possible for all pages to have free access to cookies created by other pages. As an example:

Create a cookie on the "http://www.cnblogs.com/Darren_code/" page, then the page under "/darren_code/" such as: "http://www.cnblogs.com/ Darren_code/archive/2011/11/07/cookie.html "This page will be able to access Cookie information by default.

By default, "Http://www.cnblogs.com" or "http://www.cnblogs.com/xxxx/" will not be able to access this cookie (light is useless, practice the truth ^_^).

So how to make this cookie accessible to other directories or to the parent directory, by setting the path to the cookie. Examples are as follows:

Document.cookie = "name=value;path=path"
Document.cookie = "name=value;expires=date;path=path"

Red font path is the way of cookies, the most common example is to let the cookie in the directory, so that regardless of which sub-page created by the cookie, all the pages can be accessed:

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 access between domains . The syntax is as follows:

Document.cookie = "name=value;path=path;domain=domain"

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

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

Document.cookie = "username=darren;path=/;d omain=qq.com"

Note: There must be access between the same domains, and you cannot set the value of domain to a domain name that is not a primary domain.

Three. Cookie Security

Typically, cookie information is used to pass data using an HTTP connection, which is easily viewable, so the information stored by the cookie is easily stolen. If the content passed in the cookie is important, then the encrypted data transfer is required.

So the name of this property of the cookie is "secure" and the default value is null. If the property of a cookie is secure, it passes data to and from the server over HTTPS or other security protocols. The syntax is as follows:

Document.cookie = "Username=darren;secure"

Setting the cookie to secure only guarantees that the data transfer process between the cookie and the server is encrypted, while the cookie file stored locally is not encrypted. If you want to encrypt your local cookie, you have to encrypt your data yourself.

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

Four. Cookie coding details

Originally wanted to introduce the knowledge of cookie Coding in the FAQ section, because if the coding problem is really a hole in this understanding, it is still in detail to say.

When entering cookie information, it is not possible to include special symbols such as spaces, semicolons, commas, and, in general, the storage of cookie information is encoded in an unencrypted manner. Therefore, before setting the 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 getting. If you set a cookie:

Document.cookie = name + "=" + Escape (value)

Let's look at the sentence in GetCookie () mentioned in the basic usage:

Return unescape (document.cookie.substring (c_start,c_end))

This is not to worry about because a special symbol appears in the cookie value causing the cookie information to go wrong.

Original reference:

Nievidong
Source: Http://www.cnblogs.com/Darren_code

JavaScript Learning Note--cookie

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.