JavaScript Action Cookie

Source: Internet
Author: User
Tags cookie names parent directory set cookie setcookie

Engaged in web development also some days, the cookie is a what almost can be said to understand, but the actual operation of their own is to go to search (you know), the results were despised ... So write a blog post as their own study notes, hey, the benefits of the blog is reflected in this.

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

    • Cookies are limited in size, and each cookie cannot hold more than 4kb of data, and if the cookie string is longer than 4KB, the property returns an empty string.
    • Since cookies are ultimately stored as files in the client computer, it is convenient to view and modify cookies, which is why cookies are often said to not hold important information.
    • Each cookie is formatted like this: the <cookie name >=< value >; name and value must all be valid identifiers.
    • A cookie is valid for the duration of its existence. By default, the lifetime of a cookie is ended when the browser is closed. If you want the cookie to be available after the browser has been turned off, you must set a validity period for the cookie, which is the expiration date of the cookie.
    • Alert (typeof Document.cookie) The result is a string, once I thought is an array, also made a joke ... 囧
    • Cookies have the concept of domain and path . Domain is the concept of domains, because browsers are a security-aware environment, so there is no mutual access to cookies between different domains (of course, through special settings to achieve cookie cross-domain access). The path is the concept of routing, a Web page created by the cookie can only be used in the same directory or subdirectory of the page to access all the pages, and not be in other directories to access the Web page (this sentence a bit around, look at an example to understand).
    • In fact, the way you create cookies is similar to the way you define variables, and you need to use cookie names and cookie values. Multiple cookies can be created on the same site, and multiple cookies can be stored in the same cookie file.
Cookie FAQs
    • 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.
    • If it is a page on a local disk, the Chrome console is unable to read and write cookies with JavaScript, the solution ... Change to a browser ^_^.

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. If the cookie name does not exist, then a new cookie is created, and if it exists, the value corresponding to the cookie name is modified. If you want to create a cookie multiple times, use this method again.

 Two. read operation of Cookies

To accurately read a cookie is simply to manipulate the string. Copy this code from W3school to do the analysis:

function GetCookie (c_name) {
if (document.cookie.length>0) {//query whether the cookie is empty or empty, return ""
C_start=document.cookie.indexof (c_name + "=")//through the String object's IndexOf () to check whether this cookie exists, does not exist is 1

C_start=c_start + c_name.length+1//The last +1 actually means "=", so we get the starting position of the cookie value.
C_end=document.cookie.indexof (";", C_start)//Actually I just saw IndexOf () the second parameter suddenly a little dizzy, and later remembered to indicate the location of the specified start index ... This sentence is to get the end position of the value. Because you need to consider whether it is the last item, so pass ";" Whether the number exists to judge
if (c_end==-1) c_end=document.cookie.length
Return unescape (document.cookie.substring (c_start,c_end))//The value is obtained through substring (). Want to understand unescape () to know what escape () is to do, are very important basis, want to know can be searched, at the end of the article will also explain the cookie coding details

}
Return ""
}

Of course, there are a lot of ways to read cookies, such as arrays, regular, etc., here is not to elaborate.

Three. Set the validity period of the cookie

The lifetime of the cookie that is often present in the article is the period of validity and expiration, that is, the time the cookie exists. By default, cookies are automatically cleared when the browser is closed, but we can use expires to set the expiration date of the cookie. The syntax is as follows:

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

The date value in the preceding code is a datetime string in GMT format, which is generated in the following way:

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

The above three lines of code break down into a few steps:

    • Generate an instance of date with new and 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;
    • The time is then set by the Setdate () method;
    • 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 when creating a cookie--copied from W3school. Create a function that stores information in a cookie:

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

Now our 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.

There are two ways to clear a cookie in the FAQ, and now it's time to disable the cookie by setting the period of validity to one that has expired. Since there is a way to set the expiration date, then the method of setting the expiration time will be interested friends to do their own ^_^. Below continues the deep cookie topic.

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.

Summarize

In the work more and more feel the importance of the foundation, there are a lot of technical details are to understand or understand not much. In order to improve the situation, I intend to understand the details of knowledge from the point to the surface, and then write a blog to deepen the impression, but also can share to more needy friends.

Today is Thanksgiving, thank everyone ...

If you think this article is hard, please be careful to click on the lower right corner of the recommendation, this is for us to share the greatest affirmation, thank you.

Nievidong
Source: http://www.cnblogs.com/Darren_code/
This article is copyrighted by the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link.

JavaScript Action Cookie

Related Article

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.