Cookies document.cookie

Cookies: document.cookie

In this chapter, we will cover one of the ways of storing data in the browser: cookies.

Cookies are small data strings, stored directly in the browser. They are included in the HTTP protocol. (Cookie是小数据字符串,直接存储在浏览器中。它们包含在HTTP协议中。)

As a rule, the web-server sets cookies with the help of a response Set-Cookie HTTP header. After that, the browser adds them to each request to the same domain, using the Cookie HTTP header. (通常, Web服务器在响应Set-Cookie HTTP标头的帮助下设置Cookie。之后,浏览器使用Cookie HTTP标头将它们添加到对同一域的每个请求中。)

Among the most common cases is authentication:

During the sign-in, the server applies the Set-Cookie HTTP header in the response for setting a cookie with a specific “session identifier”. The next time if the request is set to the same domain, the cookie is sent over the net by the browser, with the help of the Cookie HTTP header. In that way, the servers know who the request was made by. (在登录期间,服务器在响应中应用Set-Cookie HTTP标头,以设置具有特定“会话标识符”的Cookie。 如果下次将请求设置为同一域,则浏览器将在Cookie HTTP标头的帮助下通过网络发送Cookie。 这样,服务器就可以知道请求是由谁发出的。)

Also, you can use the document.cookie property for accessing cookies from the browser. (此外,您可以使用document.cookie属性从浏览器访问Cookie。)

Cookies can be quite tricky at times. Read on to learn more details about cookies. (饼干有时会很棘手。请继续阅读以了解有关Cookie的更多详细信息。)

Reading from Document.cookie

Reading from Document.cookie (从Document.cookie读取)

One of the most common issues is how to know whether the browser stores cookies or not. (最常见的问题之一是如何知道浏览器是否存储Cookie。)

To check the browser for cookies, you can act like this:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     // At w3cdoc.com, we use Google Analytics for statistics,
(//在w3cdoc.com ,我们使用Google Analytics进行统计,)
     // so there can be some cookies      
(//所以可以有一些饼干)
     alert(document.cookie); // cookie1=value1; cookie2=value2;...
   </script>
 </body>
</html>

The value of document.cookie involves name=value pairs that are delimited by ;. Each of them is a separate cookie. For finding a particular cookie the document.cookie can be split by ;, and then the right name will be found. Here you can use either a regular expression or array functions for doing that.

Writing to Document.cookie

Writing to Document.cookie (写入Document.cookie)

A writing operation to document.cookie updates merely the cookies that are mentioned inside it. It doesn’t touch other cookies. (Document.cookie的写入操作仅更新其中提到的Cookie。它不会碰到其他饼干。)

Let’s see an example where the call sets a cookie with the name user and value Jack:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     document.cookie = "user=Jack"; // update just the cookie named 'user'
     alert(document.cookie); // show all the cookies
   </script>
 </body>
</html>

Multiple cookies will appear after running the code above. The reason is that document.cookie= operation doesn’t overwrite all the existing cookies. All that it does is mentioning the cookie user. (运行上述代码后,将出现多个Cookie。原因是document.cookie =操作不会覆盖所有现有的Cookie。它所做的只是提及cookie用户。)

The name and the value can technically have any characters. To keep the valid formatting, you should escape them using a built-in encodeURIComponent function, like this:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     // special characters (spaces), need encoding
(//特殊字符(空格) ,需要编码)
     let name = "firstname lastname";
     let value = "Jack Down"
       // encodes the cookie as firstname%20lastname=Jack%20Down
(//将cookie编码为firstname % 20lastname = Jack % 20Down)
     document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
     alert(document.cookie); // ...; firstname%20lastname=Jack%20Down
   </script>
 </body>
</html>

Cookies include multiple options. Many of them are essential and must be set. (Cookie包括多个选项。其中许多是必不可少的,必须设置。)

They should be listed after key=value, delimited, as follows:

document.cookie = "user=Jack; path=/; expires=Mon, 11 Apr 2020 04:25:18 GMT"

Path

The path is the url path prefix (path=/mypath). The cookie is accessible under that path. It should be absolute. It is the current path, by default. (路径是url路径前缀( path =/mypath )。可在该路径下访问Cookie。它应该是绝对的。默认情况下,它是当前路径。)

In case a cookie is set with path=/admin, it can be visible at pages /admin and
/admin/something/admin/something but not /adminpage or /home. (如果设置了路径=/admin的Cookie ,则可以在pages/admin和
/admin/something/admin/something ,但不是/adminpage或/home。)

Usually, the path is to the root path=/ for making the cookie accessible from all the pages. (通常,路径是根路径=/,用于从所有页面访问Cookie。)

Domain

It’s the domain where the cookie is accessible (domain=anysite.com). But, in practice, it is not possible to set any domain. There are certain limitations. (这是可访问Cookie的域( domain = anysite.com )。但是,在实践中,无法设置任何域。有一些限制。)

A cookie can be accessed only at the domain, which sets it. (只能在设置Cookie的域中访问Cookie。)

Here is an example:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     // at anysite.com
(//在anysite.com)
     document.cookie = "user=Jack"
(document.cookie = "用户=杰克")
       // at forum.anysite.com
(//在forum.anysite.com)
     alert(document.cookie); // no user
   </script>
 </body>
</html>

So, there is no way of allowing a cookie to be accessible from another second-level domain. Hence, another.com can never receive a cookie set at site.com. But, in case of allowing subdomains, such asforum.anysite.com receive a cookie, it’s possible. Once setting a cookie at site.com, it is necessary to explicitly set domain option to the root domain such as domain=anysite.com, like this:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     // at anysite.com
(//在anysite.com)
     // make the cookie accessible on any subdomain *.anysite.com:
     document.cookie = "user=Jack; domain=w3cdoc.com"
       // later      
(稍后)
       // at forum.anysite.com
(//在forum.anysite.com)
     alert(document.cookie); // has cookie user=Jack
   </script>
 </body>
</html>

So, with the domain option, you can make a cookie acceptable at subdomains. (因此,使用域选项,您可以在子域中设置可接受的Cookie。)

Expires, Max-age

If a cookie doesn’t have one of these options, it fades away when the browser is closed. Cookies like that are known as”session cookies”. (如果Cookie没有这些选项之一,则会在浏览器关闭时消失。此类Cookie称为“会话Cookie”。)

For allowing cookies to survive the browser close, you need to set either expires or max-age option, like this:

expires=Mon, 11 Apr 2020 04:25:18 GMT

In the example above, you can see the expiration date of the cookie. It should be exactly in the mentioned format, in the GMT timezone. You can also use date.toUTCString for getting it. (在上面的示例中,您可以看到Cookie的到期日期。它应该完全按照格林威治标准时间的上述格式。您也可以使用date.toUTCString来获取它。)

In the example below, a cookie expiring in 3 days is demonstrated:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     // +3 days from now
(//从现在起+3天)
     let date = new Date(Date.now() + 3);
     date = date.toUTCString();
     document.cookie = "user=Jack; expires=" + date;
     alert(document.cookie);
   </script>
 </body>
</html>

In case you set expires to a date in the past, the cookie will be deleted. (如果您将过期设置为过去的日期, Cookie将被删除。)

Themax-age=3600 is an alternative to expires. It indicates the cookie expiration in seconds from the current moment. When it’s negative or zero, the cookie is deleted, like here:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     // cookie will disappear +2 hour from now
(//Cookie将在2小时后消失)
     document.cookie = "user=Jack; max-age=7200";
     alert(document.cookie);
     // delete cookie,let it expire right now
(//删除cookie ,让它立即过期)
     document.cookie = "user=Jack; max-age=0";
     alert(document.cookie);
   </script>
 </body>
</html>

Secure

With the secure option, if the cookie is set by https://anysite.com, it will not appear when the same site is accessed by HTTP, as https://anysite.com. Therefore, in case a cookie has sensitive content, then you shouldn’t send it over unencrypted HTTP. Here the secure option will help, as in the example below:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     // assuming you're on https:// now
     // set the cookie secure (only accessible if over HTTPS)
(//设置cookie安全(仅在通过HTTPS时可访问))
     document.cookie = "user=Jack; secure";
     alert(document.cookie);
   </script>
 </body>
</html>

Samesite

The next security attribute is samesite. It is created for protection from so-called XSRF (cross-site request forgery) attacks. The XSRF attack is a type of malicious exploit of a website, in which unauthorized commands can be transmitted from a user the web app trusts. (下一个安全属性是samesite。它是为防止所谓的XSRF (跨站点请求伪造)攻击而创建的。XSRF攻击是对网站的一种恶意利用,其中未经授权的命令可以从Web应用信任的用户传输。)

Samesite is a perfect option for protecting from such attacks but it has drawbacks too. It is ignored by older browsers ( 2017 or so). (Samesite是防止此类攻击的完美选择,但它也有缺点。较旧的浏览器( 2017年左右)会忽略它。)

So, it is not recommended to solely rely on the samesite for protection. Old browsers will be vulnerable. Using it along with other measures, such as xsrf tokens will add an extra layer to your protection. (因此,不建议仅依靠samesite进行保护。旧的浏览器将易受攻击。将它与其他措施(如xsrf令牌)一起使用将为您的保护增加一个额外的层。)

Cookie Functions (Cookie函数)

There is a small but convenient set of functions for working with cookies. It is handier than a manual modification of the document.cookie. (有一组小而方便的功能用于处理Cookie。它比手动修改document.cookie更方便。)

The shortest way to access cookies is by using regular expressions. (访问Cookie的最短方式是使用正则表达式。)

getCookie(name)

This function is used for returning the cookie with a particular name. (此函数用于返回具有特定名称的Cookie。)

Here is an example of using the getCookie(name) function:

// returns the cookie with a specific name,
// or undefined if not found
function getCookie(name) {
 let m = document.cookie.match(new RegExp(
(let m = document.cookie.match (new RegExp ()
   "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
 ));
 return matches ? decodeURIComponent(m[1]) : undefined;
}

In the example above, a new RegExp is created dynamically to correspond ; name=<value.

Also, consider that a cookie value is encoded. Therefore, getCookie applies a built-in decodeURIComponent component for decoding it. (此外,请考虑对cookie值进行编码。因此, getCookie应用内置的decodeURIComponent组件对其进行解码。)

SetCookie(name, value, options)

This method sets the cookie name to a particular value with path=/ by default, as follows:

function setCookie(name, value, options = {}) {
 options = {
   path: '/',
   // add other default values if necessary
(//根据需要添加其他默认值)
   ...options
(选项)
 };
 if (options.expires instanceof Date) {
   options.expires = options.expires.toUTCString();
 }
 let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);
 for (let optKey in options) {
   updatedCookie += "; " + optKey;
   let optValue = options[optKey];
   if (optValue !== true) {
     updatedCookie += "=" + optValue;
   }
 }
 document.cookie = updatedCookie;
}
// Example of use:
setCookie('user', 'Jack', {
 secure: true,
 'max-age': 7200
});

DeleteCookie(name)

For deleting a cookie, you can just call it with a negative expiration date, as demonstrated below:

function deleteCookie(name) {
 setCookie(name, "", {
   'max-age': -1
 })
}

While deleting or updating a cookie, you should consider that it is always necessary to use the same path and domain options as you set it with. (在删除或更新Cookie时,您应该考虑始终需要使用与设置Cookie时相同的路径和域选项。)

Summary

Summary (概要)

Cookies are an easy and versatile means to store data in the web browser. In other words, it gives “memory” to web browsers and servers. (Cookie是将数据存储在网络浏览器中的一种简单而通用的方法。换句话说,它为网络浏览器和服务器提供了“内存”。)

A cookie is a piece of data that is stored on a computer to be accessed by the browser. Almost everyone enjoys the benefits of cookies both knowingly and unknowingly. For example, saving a Facebook password and not having to type it again every time logging in, is a sign of using cookies. (Cookie是存储在计算机上以供浏览器访问的一段数据。几乎每个人都在知情和不知情的情况下享受cookie的好处。例如,保存Facebook密码而不必在每次登录时再次输入密码,就是使用Cookie的标志。)

For accessing cookies, the document.cookie property is used. (要访问Cookie ,请使用document.cookie属性。)

Small and convenient methods, such as getCookie(name), setCookie(name, value, options), and deleteCookie(name) are used to make working with cookies more efficient. (使用小而方便的方法,如getCookie (名称)、setCookie (名称、值、选项)和deleteCookie (名称) ,可以提高使用cookie的效率。)

The secure and samesite options are used for making it safer to work with cookies. (安全和samesite选项用于使使用cookie更安全。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部