On the use of document. cookie in Javascript

  • 2021-08-03 08:07:09
  • OfStack

Setting cookie

Each cookie is a name/value pair, and you can assign a string like this to document. cookie:


document.cookie="userId=828";

If you want to store multiple name/value pairs at once, you can use semicolons and spaces (;) to separate them, for example:


document.cookie="userId=828; userName=hulk";

You cannot use a semicolon (;) in the name or value of cookie Commas (,), equals (=), and spaces.

It is easy to do this in the name of cookie, but the value to be saved is uncertain. How do you store these values?

The method is to use escape () function for encoding, it can use a number of special symbols in 106-ary representation, for example, the space will be encoded as "20%", which can be stored in cookie value, and this scheme can also avoid the appearance of Chinese garbled code. For example:


document.cookie="str="+escape("I love ajax");

Equivalent to: document. cookie = "str = I% 20love% 20ajax";

When encoded with escape (), the original cookie value is decoded with unescape () after the value is fetched, as described earlier. Although document. cookie looks like a property, you can assign different values. However, it is different from a 1-like attribute. Changing its assignment does not mean losing the original value, for example, executing the following two statements in succession:


document.cookie="userId=828";
document.cookie="userName=hulk";

The browser will maintain two cookie, userId and userName, so assigning a value to document. cookie is more like executing a statement like this:


document.addCookie("userId=828");
document.addCookie("userName=hulk");

In fact, the browser sets cookie in this way. If you want to change the value of an cookie, you only need to re-assign it, for example:


document.cookie="userId=929";

This sets the value of cookie named userId to 929.

Get the value of cookie

Here's how to get the value of cookie. The value of cookie can be obtained directly from document. cookie:


var strCookie=document.cookie;

This results in a string of multiple name/value pairs separated by semicolons that include all cookie under the domain name. For example:


<script language="JavaScript" type="text/javascript">
<!--
document.cookie="userId=828";
document.cookie="userName=hulk";
var strCookie=document.cookie;
alert(strCookie);
//-->
</script>

Thus, you can only get all the cookie values once, but you can't specify the cookie name to get the specified value, which is the most troublesome part of processing cookie values.

The user must parse this string himself to get the specified cookie value. For example, to get the value of userId, you can do this:


<script language="JavaScript" type="text/javascript">
<!--
// Set two cookie
document.cookie="userId=828";
document.cookie="userName=hulk";
// Get cookie String 
var strCookie=document.cookie;
// Will be more cookie Cut into multiple names / Value pair 
var arrCookie=strCookie.split("; ");
var userId;
// Traversal cookie Array, processing each cookie Right 
for(var i=0;i<arrCookie.length;i++){
       var arr=arrCookie[i].split("=");
       // Find the name userId Adj. cookie And returns its value 
       if("userId"==arr[0]){
          userId=arr[1];
          break;
       }
}
alert(userId);
//-->
</script>

This gives you the value of a single cookie

In a similar way, one or more cookie values can be obtained, and the main trick is still the related operation of strings and arrays.

By now, all cookie are single session cookie, that is, these cookie will be lost after the browser is closed. In fact, these cookie are only stored in memory, and no corresponding hard disk files have been created.

In actual development, cookie often requires long-term preservation, such as saving the user's login state. This can be achieved with the following options:


document.cookie="userId=828;
expires=GMT_String";

Where GMT_String is a time string expressed in GMT format, this statement is to set userId, cookie, to the expiration time expressed by GMT_String. After this time, cookie will disappear and be inaccessible. For example:

If you want to set cookie to expire after 10 days, you can do this:


document.cookie="userId=828; userName=hulk";
0

Delete cookie

To delete an cookie, you can set its expiration time to 1 past time, for example:


document.cookie="userId=828; userName=hulk";
1

Specify the path where cookie can be accessed. By default, if 1 cookie is created on a page, other pages in the directory where that page is located can also be accessed

The cookie. If there are subdirectories under this directory, they can also be accessed in the subdirectories.

For example, cookie created in www. xxxx. com/html/a. html can be accessed by www. xxxx. com/html. b. html or www. xxx. com/some/c. com/d. html.

To control which directories cookie can access, you need to set cookie using the path parameter, with the following syntax:


document.cookie="userId=828; userName=hulk";
2

Where cookieDir represents the directory where cookie can be accessed. For example:


document.cookie="userId=320; path=/shop";

It means that the current cookie can only be used under the shop directory.

To make cookie available throughout the Web site, you can specify cookie_dir as the root directory, for example:


document.cookie="userId=828; userName=hulk";
4

Specify the host name and path that can access cookie, and the host name refers to different hosts under the same domain, such as www. google. com and gmail. google. com

Are two different host names. By default, an cookie created in one host cannot be accessed under another host, but it can be controlled by the domain parameter, and its syntax format is:


document.cookie="userId=828; userName=hulk";
5

Taking google as an example, to achieve cross-host access, you can write:


document.cookie="userId=828; userName=hulk";
6

This allows all hosts under google. com to access the cookie.

Comprehensive example: The processing procedure of constructing general cookie processing function cookie is complicated and has 1 definite similarity. Therefore, several functions can be defined to complete the general purpose of cookie

Operation, so as to realize code reuse. The common cookie operations and their functional implementations are listed below.

1. Add an cookie: addCookie (name, value, expireHours) This function takes three arguments: cookie name, cookie value, and how many hours after it expires.

It is agreed here that when expireHours is 0, no expiration time is set, that is, cookie disappears automatically when the browser is closed. The function is implemented as follows:


document.cookie="userId=828; userName=hulk";
7

2. Gets the cookie value for the specified name: getCookie (name)

This function returns an cookie value named name or null if it does not exist, implemented as follows:


<script language="JavaScript" type="text/javascript">
<!--
function getCookie(name){
       var strCookie=document.cookie;
       var arrCookie=strCookie.split("; ");
       for(var i=0;i<arrCookie.length;i++){
          var arr=arrCookie[i].split("=");
          if(arr[0]==name)return arr[1];
       }
       return "";
}
//-->
</script>

3. Delete cookie with the specified name: deleteCookie (name)

This function removes an cookie with the specified name, which is implemented as follows:


document.cookie="userId=828; userName=hulk";
9

Related articles: