How to use Cookies in JavaScript

Source: Internet
Author: User
Tags set cookie

How to use Cookies in JavaScript

This article describes how to use Cookies in JavaScript, including how to store and delete Cookies. For more information, see

What is Cookies?

The Web browser communicates with the server over HTTP, and HTTP is a stateless protocol. However, for a commercial website, it needs to maintain different sessions between pages. For example, after completing multiple pages, a user registration is completed. However, how can we maintain the session information of all web users.

In many cases, cookies are used to recall and track preferences, purchases, commissions, and the most effective way to require better access experience or website statistics.

How does it work?

The server sends some data to the visitor's browser in the form of a cookie. The browser can accept cookies. If so, it is a plain text record stored on the hard drive for visitors. Now, when a visitor arrives at another page on your website, the browser sends the same cookie to the server for retrieval. Once retrieved, the server knows/remembers what storage has just happened.

Cookies have plain text data records for five variable-length fields:

Expires: the date on which the cookie will expire. If this is blank, the cookie will expire when the visitor exits the browser.

Domain: the Domain Name of the website.

Path: Specifies the cookie directory or webpage. If you want to access any directory or page, the cookie is empty.

Secure: If this field contains the word "security", the cookie can only retrieve one Secure server. If this field is empty, there is no restriction.

Name = Value: Cookie is obtained in the form of key and Value pairs.

The data originally designed for CGI programming and cookies is automatically transmitted between the Web browser and the Web server, therefore, CGI scripts on the server can read and write the cookie values stored on the client.

JavaScript can also use the cookie attribute of the Document Object. JavaScript can read, create, modify, and delete Cookies or Cookies that apply to the current webpage.

Store Cookies:

The simplest way to create a cookie is to assign a string value to the document. cookie object, which is like this:

Syntax

Document. cookie = "key1 = value1; key2 = value2; expires = date ";

Here, the expires attribute option. If this property is provided with a valid date or time, then the cookie will expire on the given date or time, and then the cookie value will not be accessible.

Note: the Cookie value may not contain semicolons, commas (,), or white spaces. For this reason, you may need to use the JavaScript escape () function to encode the stored values before the cookie. In this case, you must use the corresponding scape SCAPE () function when reading the cookie value.

Read Cookies:

Reading cookies is as simple as writing, because the value of document. cookieobject is cookie. Therefore, you can use this string whenever you want to access the cookie.

The string document. cookie will continue to be separated by semicolons, where name is the name of a cookie and the value is the list of name = value pairs separated by its string values.

Set the cookie expiration date:

You can extend the life cycle of the current browser session cookie by setting the expiration date and saving the expiration date in the cookie. This can be done by setting the date and time of the expires attribute.

Example:

The following example shows how to set cookieexpiration after 1 month:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<Html>

<Head>

<Script type = "text/javascript">

<! --

Function WriteCookie ()

{

Var now = new Date ();

Now. setMonth (now. getMonth () + 1 );

Cookievalue = escape (document. myform. customer. value) + ";"

Document. cookie = "name =" + cookievalue;

Document. cookie = "expires =" + now. toUTCString () + ";"

Alert ("Setting Cookies:" + "name =" + cookievalue );

}

// -->

</Script>

</Head>

<Body>

<Form name = "formname" action = "">

Enter name: <input type = "text" name = "customer"/>

<Input type = "button" value = "Set Cookie" onclick = "WriteCookie ()"/>

</Form>

</Body>

</Html>

Delete Cookie:

If you want to delete a cookie, you can try to read the returned cookie. To do this, you only need to set the expiration date at a certain time in the past.

Example:

The following example demonstrates how to delete a cookie one month ago by setting a validity period:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<Html>

<Head>

<Script type = "text/javascript">

<! --

Function WriteCookie ()

{

Var now = new Date ();

Now. setMonth (now. getMonth ()-1 );

Cookievalue = escape (document. myform. customer. value) + ";"

Document. cookie = "name =" + cookievalue;

Document. cookie = "expires =" + now. toUTCString () + ";"

Alert ("Setting Cookies:" + "name =" + cookievalue );

}

// -->

</Script>

</Head>

<Body>

<Form name = "formname" action = "">

Enter name: <input type = "text" name = "customer"/>

<Input type = "button" value = "Set Cookie" onclick = "WriteCookie ()"/>

</Form>

</Body>

</Html>

Note: if the date is not set, you can use the setTime () function to view the new value.

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.