On the Use of document.cookie

Keywords: Javascript Google Attribute Session

Set cookie
Each cookie is a name/value pair. You can assign the following string to document.cookie:
  1. document.cookie="userId=828";  


If you want to store more than one name/value pair at a time, you can use semicolons and spaces (;), for example:
  1. document.cookie="userId=828; userName=hulk";  


Semiconductors (;), commas (,), equals (=) and spaces cannot be used in cookie names or values. Do it in the name of cookie


It's easy to do this, but the value to be saved is uncertain. How to store these values? The method is to code with escape() function, which can use hexadecimal representation of some special symbols, such as space will be coded as "20%", so that it can be stored in


In the cookie value, and the use of this scheme can also avoid the occurrence of Chinese scrambling. For example:
  1. document.cookie="str="+escape("I love ajax");  


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


When escape() is used to encode, unescape() is used to decode the original cookie value after extracting the value.


Although document.cookie looks like an attribute, it can assign different values. But unlike general attributes, changing its assignment does not mean losing the original value, such as executing the following two statements in succession:
  1. document.cookie="userId=828";  
  2. document.cookie="userName=hulk";  


At this point, the browser will maintain two cookies, userId and userName, so assigning a document.cookie is more like executing a statement like this:
  1. document.addCookie("userId=828");  
  2. document.addCookie("userName=hulk");  


In fact, browsers set cookies in this way. If you want to change the value of a cookie, you only need to reassign it, for example:
  1. document.cookie="userId=929";  


This sets the cookie value named userId to 929.


Get the value of the cookie
Here's how to get cookie values. The value of a cookie can be obtained directly from document.cookie:
  1. var strCookie=document.cookie;  


This will give you a string of semicolon-separated name/value pairs that include all cookie s under that domain name


  1. <script language="JavaScript" type="text/javascript">  
  2. <!--  
  3. document.cookie="userId=828";  
  4. document.cookie="userName=hulk";  
  5. var strCookie=document.cookie;  
  6. alert(strCookie);  
  7. //-->  
  8. </script>  




Name to get the specified value, which is the most troublesome part of cookie value processing. Users must analyze the string themselves to get the specified cookie value. For example, to get the value of userId, you can do this:


  1. <script language="JavaScript" type="text/javascript">  
  2. <!--  
  3. //Setting up two cookie s  
  4. document.cookie="userId=828";  
  5. document.cookie="userName=hulk";  
  6. //Get the cookie string  
  7. var strCookie=document.cookie;  
  8. //Cut multiple cookie s into multiple name/value pairs  
  9. var arrCookie=strCookie.split("; ");  
  10. var userId;  
  11. //Traverse the cookie array and process each cookie pair  
  12. for(var i=0;i<arrCookie.length;i++){  
  13. var arr=arrCookie[i].split("=");  
  14. //Find a cookie named userId and return its value  
  15. if("userId"==arr[0]){  
  16. userId=arr[1];  
  17. break;  
  18. }  
  19. }  
  20. alert(userId);  
  21. //-->  
  22. </script>  




Similarly, you can get the value of one or more cookie s, and the main trick is still the operation of strings and arrays.


Set an expiration date for cookie s
So far, all cookies are single session cookies, that is, when the browser closes, these cookies will be lost. In fact, these cookies are only stored in memory, but no corresponding hard disk files are created.
In practical development, cookie s often need to be preserved for a long time, such as the status of user logins. This can be achieved with the following options:
  1. document.cookie="userId=828; expires=GMT_String";  


Where GMT_String is a time string in GMT format, this statement sets the cookie userId to


GMT_String represents the expiration time beyond which cookies will disappear and be inaccessible. For example, if you want to make cookies


Set it to expire 10 days later. This can be achieved as follows:


  1. <script language="JavaScript" type="text/javascript">  
  2. <!--  
  3. //Get the current time  
  4. var date=new Date();  
  5. var expireDays=10;  
  6. //Set date to 10 days later  
  7. date.setTime(date.getTime()+expireDays*24*3600*1000);//Or you can use date.setDate(date.getDate+expireDays)  
  8. //Set userId and userName cookie s to expire after 10 days  
  9. document.cookie="userId=828; userName=hulk; expire="+date.toGMTString();  
  10. //-->  
  11. </script>  






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


  1. <script language="JavaScript" type="text/javascript">  
  2. <!--  
  3. //Get the current time  
  4. var date=new Date();  
  5. //Set date to past time  
  6. date.setTime(date.getTime()-10000);  
  7. //Delete the cookie userId  
  8. document.cookie="userId=828; expire="+date.toGMTString();  
  9. //-->  
  10. </script>  




Specify the path to accessible cookie s
By default, if a cookie is created on a page, other pages in the page's directory can also access the cookie. If there are subdirectories in this directory, they can also be accessed in the subdirectory. For example


The cookie created in www.xxxx.com/html/a.html can be either www.xxxx.com/html/b.html or


Www.xxxx.com/html/some/c.html is accessible, but cannot be accessed by www.xxxx.com/d.html.
To control the directories that cookies can access, you need to set cookies using the path parameter. The syntax is as follows:
  1. document.cookie="name=value; path=cookieDir";  


Where cookieDir represents the directory of accessible cookies. For example:
  1. document.cookie="userId=320; path=/shop";  


This means that the current cookie can only be used in the shop directory.
If you want cookies to be available throughout the site, you can specify cookie_dir as the root directory, for example:
  1. document.cookie="userId=320; path=/";  


Specify the host name of the accessible cookie
Similar to paths, hostnames refer to different hosts in the same domain, such as www.google.com and gmail.google.com. By default, cookie s created in one host can not be accessed under another host, but can be controlled by domain parameters, whose grammatical format is:
  1. document.cookie="name=value; domain=cookieDomain";  

Take google as an example, to achieve cross-host access, you can write as follows:
  1. document.cookie="name=value;domain=.google.com";  


In this way, all hosts under google.com can access the cookie.




Comprehensive example: Constructing a generic cookie handler
Cookie processing is complex and has some similarities. So you can define several functions to complete cookie generalization


Operations to achieve code reuse. Following is a list of commonly used cookie operations and their function implementations.
1. Add a cookie: addCookie(name,value,expireHours)
This function takes three parameters: the cookie name, the cookie value, and how many hours after expiration. It is stipulated here that expireHours is 0 and no expiration time is set, that is, cookies automatically disappear when the browser closes. The function is implemented as follows:


  1. <script language="JavaScript" type="text/javascript">  
  2. <!--  
  3. function addCookie(name,value,expireHours){  
  4. var cookieString=name+"="+escape(value);  
  5. //Determine whether to set expiration time  
  6.   
  7. if(expireHours>0){  
  8. var date=new Date();  
  9. date.setTime(date.getTime+expireHours*3600*1000);  
  10. cookieString=cookieString+"; expire="+date.toGMTString();  
  11. }  
  12. document.cookie=cookieString;  
  13. }  
  14. //-->  
  15. </script>  



2. Get the cookie value of the specified name: getCookie(name)
This function returns the cookie value named name and empty if it does not exist. It is implemented as follows:


  1. <script language="JavaScript" type="text/javascript">  
  2. <!--  
  3. function getCookie(name){  
  4. var strCookie=document.cookie;  
  5. var arrCookie=strCookie.split("; ");  
  6. for(var i=0;i<arrCookie.length;i++){  
  7. var arr=arrCookie[i].split("=");  
  8. if(arr[0]==name)return arr[1];  
  9. }  
  10. return "";  
  11. }  
  12. //-->  
  13.   
  14.   
  15. function getCookie(cookie_name){  
  16. var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');  
  17.   
  18.   
  19. if (results)  
  20. return (unescape(results[2]));  
  21. else  
  22. return null;  
  23. }  
  24. </script>  




3. Delete cookie s with specified names: deleteCookie(name)

This function can delete the cookie with the specified name, which is implemented as follows:

[javascript] view plain copy
 print?
  1. <script language="JavaScript" type="text/javascript">  
  2. <!--  
  3. function deleteCookie(name){  
  4. var date=new Date();  
  5. date.setTime(date.getTime()-10000);  
  6. document.cookie=name+"=v; expire="+date.toGMTString();  
  7. }  
  8. //-->  

  1. </script>  

Original: http://blog.csdn.net/a892886597/article/details/48422261

Posted by squimmy on Sat, 13 Apr 2019 00:09:34 -0700