Home  >  Article  >  Web Front-end  >  Introduction to Cookies and detailed explanation of how to operate Cookies using JavaScript

Introduction to Cookies and detailed explanation of how to operate Cookies using JavaScript

黄舟
黄舟Original
2017-02-25 13:25:371167browse

This article mainly briefly introduces the uses and operating mechanisms of the following cookies, as well as various methods of using JavaScript to operate cookies. The summary is relatively comprehensive, and I hope it can be helpful to everyone.

What is a Cookie

“A cookie is a variable that is stored on a visitor’s computer. Whenever the same computer requests a certain This cookie is sent when a page is opened. You can use JavaScript to create and retrieve the cookie value. ” – w3school

Cookies are files created by visited websites to store browsing information, such as personal information. Profile information.

From a JavaScript perspective, cookies are just 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.

Cookie Basics

Cookies have size limits. The data stored in each cookie cannot exceed 4kb. If the length of the cookie string exceeds 4kb, the Property 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 a validity period. 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 string. I once thought it was 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

come from Third-party cookies from other domains such as advertisements or pictures embedded on web pages (websites can track your usage information by using these cookies)

The basic knowledge just mentioned the issue of cookie life cycle. In fact, cookies can generally Divided into two states:

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

Cookies with expiration time set. 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 your computer for days, months or even years.

There are two ways to clear cookies:

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

Clear cookies by setting the cookie validity period

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 as much as possible.

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 ; One 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

要精确的对 cookie 进行读取其实很简单,就是对字符串进行操作。从w3school上copy这段代码来做分析:

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 ""
  }

当然想实现读取cookie的方法还有不少,比如数组,正则等,这里就不往细说了。

三.设置cookie的有效期

文章中常常出现的 cookie 的生命周期也就是有效期和失效期,即 cookie 的存在时间。在默认的情况下,cookie 会在浏览器关闭的时候自动清除,但是我们可以通过expires来设置 cookie 的有效期。语法如下:

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

上面代码中的date值为GMT(格林威治时间)格式的日期型字符串,生成方式如下:

var _date = new Date();
_date.setDate(_date.getDate()+30);
_date.toGMTString();

上面三行代码分解为几步来看:

通过new生成一个Date的实例,得到当前的时间;

getDate()方法得到当前本地月份中的某一天,接着加上30就是我希望这个cookie能过在本地保存30天;

接着通过setDate()方法来设置时间;

最后 用toGMTString()方法把Date对象转换为字符串,并返回结果

通过下面这个完整的函数来说明在创建 cookie 的过程中我们需要注意的地方 – 从w3school复制下来的。创建一个在 cookie 中存储信息的函数:

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)

现在我们这个函数是按照天数来设置cookie的有效时间,如果想以其他单位(如:小时)来设置,那么改变第三行代码即可:

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

这样设置以后的cookie有效期就是按照小时为单位的。

常见问题中有提到清除 cookie 的两种方法,现在要说的是使 cookie 失效,通过把有效期的时间设置为一个已过期的时间。既然已经有了设置有效期的方法,那么设置失效期的方法就请感兴趣的朋友自己动手了^_^。下面继续比较深的cookie话题。

Cookie 高级篇

一.cookie 路径概念

在基础知识中有提到 cookie 有域和路径的概念,现在来介绍路径在 cookie 中的作用。

cookie 一般都是由于用户访问页面而被创建的,可是并不是只有在创建 cookie 的页面才可以访问这个 cookie。

默认情况下,只有与创建 cookie 的页面在同一个目录或子目录下的网页才可以访问,这个是因为安全方面的考虑,造成不是所有页面都可以随意访问其他页面创建的 cookie。举个例子:

在 “http://www.php.cn/” 这个页面创建一个cookie,那么在”/Darren_code/”这个路径下的页面如: “http://www.php.cn/”这个页面默 认就能取到cookie信息。

可在默认情况下, “http://www.php.cn/”或者 “http://www.php.cn/” 就不可以访问这个 cookie(光看没用,实践出真理^_^)。

那么如何让这个 cookie 能被其他目录或者父级的目录访问类,通过设置 cookie 的路径就可以实现。例子如下:

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

红色字体path就是 cookie 的路径,最常用的例子就是让 cookie 在跟目录下,这样不管是哪个子页面创建的 cookie,所有的页面都可以访问到了:

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

二.cookie 域概念

路径能解决在同一个域下访问 cookie 的问题,咱们接着说 cookie 实现同域之间访问的问题。语法如下:

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

红色的domain就是设置的 cookie 域的值。

例如 ”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值



 以上就是Cookie介绍及JavaScript操作Cookie方法详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!





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