Javascript 简明教程

JavaScript and Cookies

What are Cookies ?

在 JavaScript 中,cookie 是存储在用户 Web 浏览器中的数据块。cookie 存储在浏览器内的键值对中。我们可以使用 document 对象的 cookie 属性来操作 cookie。我们可以使用 cookie 属性在键值对中设置或存储 cookie。我们可以使用 document 的 cookie 属性读取 cookie,并使用解构提取所需信息。

In JavaScript, cookies are piece of data stored in the user’s web browser. The cookies are stored in the key-value pair inside the browser. We can manipulate the cookies using cookie property of document object. We can set or store a cookie in key-value pair using the cookie property. We can read cookies using document’s cookie property and extract the desired information using destructuring.

Why are Cookies needed?

Web 浏览器和服务器使用 HTTP 协议进行通信,而 HTTP 是无状态协议。但对于商业网站来说,需要在不同的页面之间维护会话信息。

Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages.

例如,你在某个特定网页上的某个特定网站上登录过。同一网站的其他网页如何知道你已完成登录过程?在这种情况下,就会使用 cookie。

For example, you have logged in to a particular website on a particular web page. How do other webpages of the same website know your state that you have already completed the logged-in process? In this case, cookies are used.

在许多情况下,使用 cookie 是记忆和跟踪偏好、购买、佣金和其他信息最有效的方法,而这些信息对于提升访问者体验或网站统计至关重要。

In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.

有时,cookie 也用于高速缓存,提高网站或应用程序的性能。

Sometimes, cookies are also used for caching, increasing the website or application performance.

How It Works ?

您的服务器以 cookie 的形式向访问者的浏览器发送部分数据。浏览器可能会接收该 cookie。如果接受,它会以纯文本记录的形式存储在访问者的硬盘上。现在,当访问者访问您网站上的另一个页面时,浏览器会向服务器发送相同的 cookie 以供检索。检索后,您的服务器会知道/记住之前存储的内容。

Your server sends some data to the visitor’s browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor’s hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.

Cookie 是纯文本数据记录,包含 5 个可变长度字段:

Cookies are a plain text data record of 5 variable-length fields −

  1. Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.

  2. Domain − The domain name of your site.

  3. Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.

  4. Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.

  5. Name=Value − Cookies are set and retrieved in the form of key-value pairs

Cookie 的最初设计是为了 CGI 编程。Cookie 中包含的数据会自动在 Web 浏览器和 Web 服务器之间传输,这样服务器上的 CGI 脚本就能读取和写入存储在客户端上的 Cookie 值。

Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client.

Setting/ Storing Cookies

JavaScript 可以使用 cookie 对象的 Document 属性来操作 cookie。JavaScript 可以读取、创建、修改和删除应用于当前网页的 cookie。

JavaScript can manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.

创建 Cookie 的最简单的方法是将一个字符串值分配给 document.cookie 对象,如下所示。

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

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

这里的 expires 属性是可选的。如果您使用有效日期或时间提供这个属性,则 Cookie 将在给定的日期或时间过期,此后无法再访问 Cookie 的值。

Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.

cookie 字符串包含以分号分隔的键值对。

The cookie string contains the key-value pairs separated by the semi-colons.

Note - Cookie 值不能包含分号、逗号或空格。由于此原因,您可能希望在将 JavaScript escape() 函数编码后存储在 Cookie 中之前使用该函数。如果您这么做,在读取 Cookie 值时,您还必须使用相应的 unescape() 函数。

Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value.

Example

尝试以下操作。它在输入 Cookie 中设置一个客户名称。

Try the following. It sets a customer name in an input cookie.

<html>
   <head>
      <script type = "text/javascript">
         function WriteCookie() {
            if( document.myform.customer.value == "" ) {
               alert("Enter some value!");
               return;
            }
            cookievalue = escape(document.myform.customer.value) + ";";
            document.cookie = "name=" + cookievalue;
            document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
      </script>
   </head>

   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
      </form>
   </body>
</html>

Output

现在,您的计算机有一个名为 name 的 Cookie。您可以使用多个以逗号分隔的键值对来设置多个 Cookie。

Now your machine has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma.

Reading Cookies

读取 Cookie 和编写 Cookie 同样简单,因为 document.cookie 对象的值就是 Cookie。因此,每次您要访问 Cookie 时,都可以使用这个字符串。document.cookie 字符串将保留一个由分号分隔的名值对列表,其中 name 是 Cookie 的名称,value 是它的字符串值。

Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value.

您可以使用字符串的 split() 函数将字符串分解为键和值,如下所示 -

You can use strings' split() function to break a string into key and values as follows −

Example

尝试以下示例以获取所有 Cookie。

Try the following example to get all the cookies.

<html>
   <head>
      <script type = "text/javascript">
         function ReadCookie() {
            var allcookies = document.cookie;
            document.write ("All Cookies : " + allcookies );

            // Get all the cookies pairs in an array
            cookiearray = allcookies.split(';');

            // Now take key value pair out of this array
            for(var i=0; i<cookiearray.length; i++) {
               name = cookiearray[i].split('=')[0];
               value = cookiearray[i].split('=')[1];
               document.write ("Key is : " + name + " and Value is : " + value);
            }
         }
      </script>
   </head>

   <body>
      <form name = "myform" action = "">
         <p> click the following button and see the result:</p>
         <input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
      </form>
   </body>
</html>

Note - 这里 lengthArray 类的某个方法,它返回数组的长度。我们在单独章节中讨论数组。在讨论之前,请尝试理解一下。

Note − Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time, please try to digest it.

Note - 您的计算机中可能已经设置了其他一些 Cookie。以上代码将显示计算机中设置的所有 Cookie。

Note − There may be some other cookies already set on your machine. The above code will display all the cookies set on your machine.

Setting Cookies Expiry Date

您可以通过设置一个过期日期并在 Cookie 中保存过期日期来将 Cookie 的生存期延长到当前浏览器会话之后。这可以通过设置 ‘expires’ 属性为一个日期和时间来实现。

You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the ‘expires’ attribute to a date and time.

Example

尝试以下示例。它说明如何将 Cookie 的过期日期延长 1 个月。

Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.

<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() + ";"
            document.write ("Setting Cookies : " + "name=" + cookievalue );
         }
      </script>
   </head>

   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>
   </body>
</html>

Output

有时,您会希望删除一个 Cookie,以便后续尝试读取 Cookie 时没有任何返回结果。要做到这一点,您只需要将过期日期设置为过去的时间。

Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiry date to a time in the past.

Example

尝试以下示例。它说明如何通过将过期日期设置为当前日期之前的一个月来删除 Cookie。

Try the following example. It illustrates how to delete a cookie by setting its expiry date to one month behind the current date.

<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() + ";"
            document.write("Setting Cookies : " + "name=" + cookievalue );
         }
      </script>
   </head>

   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>
   </body>
</html>

Output

Updating Cookies

要更新 cookie 中的特定键值对,可以将新的键值对分配给 document.cookie 属性。在此处,你需要确保使用的是要更新其值的键。

To update the particular key-value pair in the cookie, you can assign new key-value pair to the document.cookie property. Here, you need to ensure you are using the same key whose value you want to update.

Syntax

请遵循以下语法来更新 cookie。

Follow the syntax below to update the cookies.

document.cookie="key1=value1";

在上述语法中,我们正在更新“key”cookie 的值。

In the above syntax, we are updating the value of the ‘key’ cookie.

Example

在下面的代码中,单击设置 Cookie 按钮以设置 Cookie。它会将 cartItem 的观察值设置为 10000,而 price 的值为 10000。

In the code below, click the set cookies button to set the cookies. It will set the watch value for the cartItem and 10000 for the price.

然后,你可以单击获取 Cookie 按钮,具体观察这些 Cookie。

After that, you can click the get cookies button to observe the cookies.

接下来,你可以单击更新 Cookie 按钮以更新 Cookie。它会将 cartItem 值更改为 bag 并将 price 值更改为 5000。

Next, you can click on the update cookies button to update the cookies. It will change the cartItem value to bag and the price to 5000.

现在,再次单击获取 Cookie 按钮以获取更新的 Cookie 值。

Now, click the get cookies button again to get the updated cookie value.

<html>
<body>
<p id = "output"> </p>
<button onclick = "setCookies()"> Set Cookie </button> <br> <br>
<button onclick = "updateCookies()"> Update Cookie </button> <br> <br>
<button onclick = "getCookies()"> Get Cookies </button>
<script>
let output = document.getElementById("output");
function setCookies() {
  document.cookie = "cartItem=watch";
  document.cookie = "price=10000";
}
function updateCookies() {
  // Updating cookies
  document.cookie = "cartItem=bag";
  document.cookie = "price=5000";
}
function getCookies() {
  //Spliting the cookie string
  const allCookies = document.cookie.split("; ");
  output.innerHTML = "The cookie data are : <br>";

  for (const cookie of allCookies) {
    const [key, value] = cookie.split("=");
    if (key == "cartItem" || key == "price") {
       output.innerHTML += `${key} : ${decodeURIComponent(value)} <br>`;
    }
  }
}
</script>
</body>
</html>