JavaScript: writing, reading, and deleting cookies _ javascript skills

Source: Internet
Author: User
A cookie has a validity period. By default, the lifecycle of a cookie ends when the browser is closed. This article describes how to use javascript to perform simple operations on the cookie, for example, for writing and deleting cookies, the code is simple and easy to understand. If you need a friend's reference, you should first introduce the basic knowledge of cookies before introducing the body.

First understand what is cookie

"Cookie is a variable stored on the visitor's computer. This cookie is sent every time a computer requests a page through a browser. You can use JavaScript to create and retrieve cookie values ."

A cookie is a file created on a visited website. It is used to store browsing information, such as personal information.

From the JavaScript perspective, cookies are strings. This information is stored in the client computer and used to transmit information between the client computer and the server.

In JavaScript, you can use document. cookie to read or set this information. Because cookies are mostly used for communication between the client and the server, in addition to JavaScript, the server language (such as PHP) can also access cookies.

Basic Cookie knowledge

A cookie has a size limit. Each cookie cannot store more than 4 kb of data. If the cookie string length exceeds 4 kb, this attribute returns an empty string.

Because cookies are stored in the client computer as files, it is convenient to view and modify cookies. This is why Cookies cannot store important information.

The format of each cookie is as follows: = <值> ; Names and values must both be valid identifiers.

Cookie is valid. By default, the lifecycle of a cookie ends when the browser is closed. If you want to use a cookie after it is disabled by the browser, you must set a validity period for the cookie, that is, the expiration date of the cookie.

Alert (typeof document. cookie) returns a string. I thought it was an array and made a joke...

Cookie has the concept of domain and path. Domain is the concept of domain. Because browsers are secure environments, different domains cannot access each other's cookies (of course, cross-origin cookie access can be achieved through special settings ). PATH is the concept of routing. A cookie created by a webpage can only be accessed by all webpages in the same directory or subdirectory as the webpage, it cannot be accessed by web pages in other directories (this sentence is a bit difficult, so I will understand it after looking at an example later ).

In fact, the method for creating a cookie is similar to that for defining a variable. Both cookie names and cookie values are required. Multiple cookies can be created for the same website, and multiple cookies can be stored in the same cookie file.

Cookie FAQs

There are two types of cookies:

The cookie set for the current website you are browsing

Third-party cookies from other domain sources such as advertisements or Images embedded on webpages (websites can use these cookies to track your usage information)
As mentioned in the basic knowledge, the cookie lifecycle can be roughly divided into two statuses:

Temporary cookies. During the current use process, the website will store some of your personal information. When the browser is closed, the information will be deleted from the computer.
Set the cookie with the expiration time. Even if the browser is closed, the information industry will still be in the computer. Such as the logon name and password, you do not need to log on to a specific site each time. This cookie can be retained on a computer for several days, months, or even years.

There are two methods to clear cookies:

Clear cookies using browser Tools (with third-party tools, the browser also has this function)
Clear the cookie by setting the cookie Validity Period

Note: deleting a cookie may cause some webpages to fail to run normally.

The browser can accept and reject access cookies through settings.

For functional and performance reasons, we recommend that you reduce the number of cookies and use small cookies whenever possible.

Details about cookie encoding will be discussed separately in the cookie advanced section.

For a page on a local disk, the chrome console cannot use JavaScript to read and write cookies. The solution is to change the browser to pai_^.

This section describes some simple javascript operations on cookies, such as writing and deleting cookies.

The code is very simple and suitable for reference by friends who are not familiar with basic cookie operations.

1. Write cookie:

// Two parameters: one is the name of the cookie and the other is the value function SetCookie (name, value) {var Days = 30; // This cookie will be saved for 30 days var exp = new Date (); // new Date ("December 31,999 8"); exp. setTime (exp. getTime () + Days * 24x60*60*1000); document. cookie = name + "=" + escape (value) + "; expires =" + exp. toGMTString ();}

Ii. Read cookie:

// Function getCookie (name) {var arr = document. cookie. match (new RegExp ("(^ |)" + name + "= ([^;] *) (; | $)"); if (arr! = Null) return unescape (arr [2]); return null ;}

3. Delete cookies:

// Delete cookiefunction delCookie (name) {var exp = new Date (); exp. setTime (exp. getTime ()-1); var cval = getCookie (name); if (cval! = Null) document. cookie = name + "=" + cval + "; expires =" + exp. toGMTString ();}

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.