Home  >  Article  >  Web Front-end  >  javaScript operation cookie method

javaScript operation cookie method

伊谢尔伦
伊谢尔伦Original
2016-11-24 09:58:02965browse

What are Cookies

"A cookie is a variable stored on a visitor's computer. This cookie is sent each time the same computer requests a page through a browser. You can use JavaScript to create and retrieve cookies value. ” – w3school

A cookie is a file created by a visited website to store browsing information, such as profile information.

From a JavaScript perspective, cookies are some string information. This information is stored in the client's computer and is used to transfer information between the client computer and the server.

This information can be read or set through document.cookie in JavaScript. Since cookies are mostly used for communication between the client and the server, in addition to JavaScript, server-side languages ​​(such as PHP) can also access cookies.

Basics of Cookies

Cookies have a size limit. The data stored in each cookie cannot exceed 4kb. If the length of the cookie string exceeds 4kb, this attribute will return an empty string.

Since cookies are ultimately stored in the client computer in the form of files, it is very convenient to view and modify cookies. This is why it is often said that cookies cannot store important information.

The format of each cookie is like this: f8d1c218235c8692ef184e49bd591df4=8487820b627113dd990f63dd2ef215f3; both name and value must be legal identifiers.

Cookies have an expiration date. By default, the life cycle of a cookie ends when the browser is closed. If you want the cookie to be usable after the browser is closed, you must set a validity period for the cookie, which is the cookie's expiration date.

alert(typeof document.cookie) The result is a string. I once thought it was an array, and I even made a joke...囧

cookie has the concept of domain and path. Domain is the concept of domain. Because the browser is a security-conscious environment, different domains cannot access cookies from each other (of course, cross-domain access to cookies 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 this webpage, but cannot be accessed by webpages in other directories (this sentence is a bit confusing, I will look at it later) It’s easier to understand with an example).

In fact, the way to create cookies is somewhat similar to the way to define variables. Both require the use of cookie names and cookie values. The same website can create multiple cookies, and multiple cookies can be stored in the same cookie file.

Cookie FAQ

There are two types of cookies:

Cookies set by the current website you are browsing

Cookies from third-party sources that embed ads or images on web pages, etc. from other domains (websites can be tracked by using these cookies Your usage information)

Just now the basic knowledge mentioned the issue of cookie life cycle. In fact, cookies can be roughly divided into two states:

Temporary cookies. The website will store some of your personal information during the current use, and this information will also be deleted from the computer when the browser is closed

Set a cookie with an expiration time. Even if the browser is closed, this information will still be on the computer. Such as login name and password, so you don't have to log in every time you go to a specific site. This kind of cookie can remain on the computer for days, months or even years.

There are two ways to clear cookies:

Clear cookies through browser tools (there are third-party tools, and the browser itself also has this function)

Clear cookies by setting the cookie expiration date

Note: Deleting cookies may sometimes cause some web pages to not function properly

Browsers can be set to accept and deny access to cookies.

For functional and performance reasons, it is recommended to reduce the number of cookies used and try to use small cookies.

The details of cookie encoding will be introduced separately in the advanced cookie chapter.

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

Basic usage of Cookie

1. Simple access operation

When using JavaScript to access cookies, you must use the cookie attribute of the Document object; a line of code introduces how to create and modify a cookie:

document.cookie = 'username=Darren';

In the above code, 'username' represents the cookie name, and 'Darren' represents the value corresponding to this name. If the cookie name does not exist, then a new cookie is created; if it exists, the value corresponding to the cookie name is modified. If you want to create cookies multiple times, just use this method repeatedly.

2. Cookie reading operation

To accurately read cookies is actually very simple, just operate on strings. Copy this code from w3school for analysis:

function getCookie(c_name){
    if (document.cookie.length>0){  //先查询cookie是否为空,为空就return ""
      c_start=document.cookie.indexOf(c_name + "=")  //通过String对象的indexOf()来检查这个cookie是否存在,不存在就为 -1  
      if (c_start!=-1){
        c_start=c_start + c_name.length+1  //最后这个+1其实就是表示"="号啦,这样就获取到了cookie值的开始位置
        c_end=document.cookie.indexOf(";",c_start)  
        //其实我刚看见indexOf()第二个参数的时候猛然有点晕,后来想起来表示指定的开始索引的位置...这句是为了得到值的结束位置。
        //因为需要考虑是否是最后一项,所以通过";"号是否存在来判断
        if (c_end==-1) c_end=document.cookie.length  
        return unescape(document.cookie.substring(c_start,c_end))  
        //通过substring()得到了值。想了解unescape()得先知道escape()是做什么的,都是很重要的基础,想了解的可以搜索下,在文章结尾处也会进行讲解cookie编码细节
      }
    }
    return ""
  }

Of course, there are many ways to read cookies, such as arrays, regular expressions, etc., so I won’t go into details here.

3. Set the validity period of the cookie

The life cycle of cookies that often appears in articles is the validity period and expiration period, that is, the existence time of the cookie. By default, cookies are automatically cleared when the browser is closed, but we can set the validity period of the cookie through expires. The syntax is as follows:

document.cookie = "name=value;expires=date";

The date value in the above code is a date string in GMT (Greenwich Mean Time) format, and the generation method is as follows:

var _date = new Date();

_date.setDate(_date.getDate()+30);

_date.toGMTString();

The above three lines of code are broken down into several steps:

Generate a Date instance through new to get the current time;

getDate() method gets a certain day in the current local month, and then add 30. I hope this cookie can be saved locally for 30 days;

Then Set the time through the setDate() method;

Finally, use the toGMTString() method to convert the Date object into a string and return the result

The following complete function will illustrate what we need to pay attention to in the process of creating cookies – Copied from w3school. Create a function that stores information in cookies:

function setCookie(c_name, value, expiredays){
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
//使用方法:setCookie('username','Darren',30)

Now our function sets the validity time of the cookie according to the number of days. If you want to set it in other units (such as hours), then change the third line of code:

exdate.setHours(exdate.getHours() + expiredays);

The validity period of the cookie set in this way will be based on hours.

There are two methods of clearing cookies mentioned in the FAQ. What we are going to talk about now is to invalidate cookies by setting the validity period to an expired time. Now that there is a method to set the validity period, interested friends are asked to do it themselves ^_^. Let’s continue with the more in-depth topic of cookies.

Cookie Advanced Chapter

1. Cookie path concept

In the basic knowledge, it is mentioned that cookies have the concept of domain and path. Now let’s introduce the role of path in cookies.

Cookies are generally created when users visit a page, but this cookie is not only accessible on the page where the cookie is created.

By default, only web pages in the same directory or subdirectory as the page that created the cookie can be accessed. This is due to security considerations, so not all pages can freely access cookies created by other pages. For example:

Create a cookie on the page "http://www.jb51.net/Darren_code/", then the page under the path "/Darren_code/" will be like: "http://www.jb51. net/Darren_code/archive/2011/11/07/Cookie.html" This page can obtain cookie information by default.

By default, "http://www.jb51.net" or "http://www.jb51.net/xxxx/" cannot access this cookie (just looking at it is useless, practice the truth^ _^).

So how to make this cookie accessible to other directories or parent directories can be achieved by setting the path of the cookie. The example is as follows:

document.cookie = "name=value;path=path"

document.cookie = "name=value;expires=date;path=path"

The path in red font is the cookie path, the most common example is to put the cookie in the following directory, so that no matter which sub-page creates the cookie, all pages can access it:

document.cookie = "name=Darren;path=/" ;

2. Cookie domain concept

path can solve the problem of accessing cookies in the same domain. Let's go on to talk about the problem of cookies realizing access between the same domains. The syntax is as follows:

document.cookie = "name=value;path=path;domain=domain";

The red domain is the value of the cookie domain set.

例如 ”www.qq.com” 与 “sports.qq.com” 公用一个关联的域名”qq.com”,我们如果想让 “sports.qq.com” 下的cookie被 ”www.qq.com” 访问,我们就需要用到 cookie 的domain属性,并且需要把path属性设置为 “/”。例:

document.cookie = "username=Darren;path=/;domain=qq.com";

   

注:一定的是同域之间的访问,不能把domain的值设置成非主域的域名。

三.cookie 安全性

通常 cookie 信息都是使用HTTP连接传递数据,这种传递方式很容易被查看,所以 cookie 存储的信息容易被窃取。假如 cookie 中所传递的内容比较重要,那么就要求使用加密的数据传输。

所以 cookie 的这个属性的名称是“secure”,默认的值为空。如果一个 cookie 的属性为secure,那么它与服务器之间就通过HTTPS或者其它安全协议传递数据。语法如下:

document.cookie = "username=Darren;secure"

    把cookie设置为secure,只保证 cookie 与服务器之间的数据传输过程加密,而保存在本地的 cookie文件并不加密。如果想让本地cookie也加密,得自己加密数据。

注:就算设置了secure 属性也并不代表他人不能看到你机器本地保存的 cookie 信息,所以说到底,别把重要信息放cookie就对了,囧…

四.cookie 编码细节

原本来想在常见问题那段介绍cookie编码的知识,因为如果对这个不了解的话编码问题确实是一个坑,所以还是详细说说。

在输入cookie信息时不能包含空格,分号,逗号等特殊符号,而在一般情况下,cookie 信息的存储都是采用未编码的方式。所以,在设置 cookie 信息以前要先使用escape()函数将 cookie 值信息进行编码,在获取到 cookie 值得时候再使用unescape()函数把值进行转换回来。如设置cookie时:

document.cookie = name + "="+ escape (value);

    再看看基础用法时提到过的getCookie()内的一句:

return unescape(document.cookie.substring(c_start,c_end));

    这样就不用担心因为在cookie值中出现了特殊符号而导致 cookie 信息出错了。

个人代码

/*设置Cookie*/
function setCookie(c_name, value, expiredays, path, domain, secure) { 
 var exdate = new Date(); //获取当前时间 
 exdate.setDate(exdate.getDate() + expiredays);  //过期时间  
 document.cookie = c_name + "=" + //cookie名称
 escape(value) + //将cookie值进行编码
 ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + //设置过期时间
 ((path == null) ? '/' : ';path=' + path) + //设置访问路径
 ((domain == null) ? '' : ';domain=' + domain) + //设置访问域
 ((secure == null) ? '' : ';secure=' + secure);  //设置是否加密
};
setCookie('test', 'name=sheng;sex=men;lancer=dullbear', 30);
setCookie('bb', 'name=sheng;sex=men', 30);
/*获取Cookie*/
function getCookie(c_name, index) {
 var cookies = document.cookie; //获取cookie值
 var cookieLen = cookies.length; //获取cookie长度
 if (cookieLen > 0) { //cookie不为空时
  var c_start = cookies.indexOf(c_name + '='); //查找需要cookie值在cookie中序号
  if (c_start > -1) { //cookie值存在时
   c_start += c_name.length + 1; //获取cookie值开始序列号
   var c_end = cookies.indexOf(';', c_start); //获取cookie值结束序列号
   if (c_end == -1) { //当cookie是最后一个时
    c_end = cookieLen; //设置cookie值结束序列号为cookie长度
   };
   var cookieStr = unescape(cookies.substring(c_start, c_end)); //获取解码cookie值
   var cookieObj = cookieStr.split(';'); //分割cookie值
   index = ((index == null) ? 0 : index); //判断index是否传值
   var goalObj = cookieObj[index]; //索引数组
   var goalStr = goalObj.split('=');
   var getcook = goalStr[1]; //获取需要取的cookie值
   return getcook;
  };
 } else {
  console.log('页面没有cookie');
 }
};
alert(getCookie('test', 0)); //打印查询cookie值

   


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn