Home >Web Front-end >JS Tutorial >Detailed analysis of the use of cookies in js_javascript skills

Detailed analysis of the use of cookies in js_javascript skills

WBOY
WBOYOriginal
2016-05-16 19:04:13866browse

Cookie Overview
In the previous section, an immutable framework was used to store the shopping column data, while the product display page was constantly changing, although this could achieve a simulated global variable. Functional, but not rigorous. For example, if you right-click within the navigation frame page and click the [Refresh] command in the shortcut menu, all JavaScript variables will be lost. Therefore, to implement strict cross-page global variables, this method is not feasible. Another mechanism in JavaScript: cookies can meet the requirements of true global variables.

Cookie is a mechanism provided by the browser, which provides the cookie attribute of the document object to JavaScript. It can be controlled by JavaScript and is not a property of JavaScript itself. A cookie is a file stored on the user's hard drive. This file usually corresponds to a domain name. When the browser accesses the domain name again, the cookie is made available. Therefore, cookies can span multiple web pages under one domain name, but cannot be used across multiple domain names.

Different browsers implement cookies differently, but their properties are the same. For example, in Windows 2000 and Windows xp, cookie files are stored in the documents and settingsuserNamecookie folder. The usual naming format is: userName@domain.txt.

The cookie mechanism stores information on the user's hard drive, so it can be used as a global variable. This is one of its biggest advantages. It can be used in the following situations.

(1) Save user login status. For example, the user ID is stored in a cookie so that the user does not need to log in again when he visits the page next time. Many forums and communities now provide this function. Cookies can also set an expiration time. When the time limit expires, the cookie will automatically disappear. Therefore, the system can often prompt users to stay logged in: common options are one month, three months, one year, etc.

(2) Track user behavior. For example, a weather forecast website can display local weather conditions based on the region selected by the user. If you need to select the location every time, it will be cumbersome. When cookies are used, it will become more user-friendly. The system can remember the area visited last time. When the page is opened next time, it will automatically display the last user. Weather conditions in your area. Because everything is done in the background, such a page is as if it is customized for a certain user and is very convenient to use.

(3) Customized page. If the website provides the function of changing the skin or changing the layout, cookies can be used to record the user's options, such as background color, resolution, etc. When the user visits next time, the interface style of the last visit can still be saved.

(4) Create a shopping cart. Just like in the previous example, cookies are used to record the items that the user needs to purchase, and they can be submitted uniformly during checkout. For example, Taobao uses cookies to record the products that users have browsed so that they can be compared at any time.

Of course, the above applications are only some of the applications that cookies can complete, and there are more functions that require global variables. The disadvantages of cookies mainly focus on security and privacy protection. Mainly include the following types:

(1) Cookies may be disabled. When a user pays great attention to personal privacy protection, he is likely to disable the cookie function of the browser;
(2) Cookies are related to the browser. This means that even if you visit the same page, cookies saved by different browsers cannot be accessed from each other;
(3) Cookies may be deleted. Because each cookie is a file on the hard disk, it is likely to be deleted by the user;
(4) Cookie security is not high enough. All cookies are recorded in files in the form of plain text, so if you want to save username, password and other information, it is best to encrypt it in advance.

Set cookies
Each cookie is a name/value pair. You can assign the following string to document.cookie:

document.cookie ="userId=828";
If you want to store multiple name/value pairs at one time, you can use semicolons and spaces (; ) to separate them, for example:

document.cookie="userId=828; userName=hulk";
Semicolons (;), commas (,), equal signs (=) and spaces cannot be used in cookie names or values. It's easy to do this in the name of the cookie, but the value to be saved is undefined. How to store these values? The method is to use the escape() function to encode, which can use hexadecimal representation of some special symbols. For example, spaces will be encoded as "20%", which can be stored in the cookie value, and using this solution can also avoid The emergence of Chinese garbled characters. For example:

Copy code The code is as follows:

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

is equivalent to:

Copy code The code is as follows:

document.cookie="str=I love ajax";

When using escape() encoding, you need to use unescape() to decode after taking out the value to get the original cookie value, which has been introduced before.

Although document.cookie looks like a property and can be assigned different values. But it is different from general attributes. Changing its assignment does not mean losing the original value. For example, executing the following two statements continuously:

Copy code The code is as follows:

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

At this time, the browser will maintain two cookies, namely userId and userName, so assigning a value to document.cookie is more like executing a statement like this:

Copy code The code is as follows:

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

In fact, the browser sets cookies in this way. If you want to change the value of a cookie, you only need to reassign it, for example:

document.cookie="userId =929";
This sets the cookie value named userId to 929.

Get the value of the cookie
The following describes how to get the value of the cookie. The value of the cookie can be obtained directly from document.cookie:

var strCookie=document.cookie;
This will get a string consisting of multiple name/value pairs separated by semicolons. The / value pair includes all cookies under this domain name. For example:
Copy code The code is as follows:



As can be seen from the output, all cookie values ​​can only be obtained at once, but not Specifying the cookie name to get the specified value is the most troublesome part of dealing with cookie values. Users must analyze this string themselves to obtain the specified cookie value. For example, to obtain the value of userId, you can do this:
Copy code The code is as follows:



This way you get the value of a single cookie.

Using a similar method, you can get the value of one or more cookies. The main technique is still the related operations of strings and arrays.

Set an expiration date for cookies
Up to now, all cookies are single-session cookies, that is, these cookies will be lost after the browser is closed. In fact, these cookies are just Stored in memory without creating corresponding hard disk files.

In actual development, cookies often need to be saved for a long time, such as saving the user's login status. This can be achieved using the following options:

document.cookie="userId=828; expiress=GMT_String";
where GMT_String is a time string expressed in GMT format. This statement is to replace userId This cookie is set to the expiration time represented by GMT_String. After this time, the cookie will disappear and become inaccessible. For example: If you want to set a cookie to expire after 10 days, you can do it like this:
Copy code The code is as follows:



Delete cookie
In order to delete a cookie, you can set its expiration time to a time in the past, for example:
Copy Code The code is as follows:



Specify the path where the cookie can be accessed
By default, if a cookie is created on a page, the cookie can also be accessed by other pages in the directory where the page is located. If there are subdirectories under this directory, you can also access it in the subdirectories. For example, a cookie created in www.xxxx.com/html/a.html can be accessed by www.xxxx.com/html/b.html or www.xxx.com/html/some/c.html, but Cannot be accessed by www.xxxx.com/d.html.

In order to control the directories that cookies can access, you need to use the path parameter to set cookies. The syntax is as follows:

document.cookie="name=value; path=cookieDir";
where cookieDir means Directory of accessible cookies. For example:

document.cookie="userId=320; path=/shop";
means that the current cookie can only be used in the shop directory.

If you want to make cookies available throughout the website, you can specify cookie_dir as the root directory, for example:
Copy code The code is as follows:

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

Specify the host name that can access the cookie
and the path are similar , the host name refers to different hosts under the same domain, for example: www.google.com and gmail.google.com are two different host names. By default, cookies created in one host cannot be accessed in another host, but they can be controlled through the domain parameter. The syntax format is:

document.cookie="name =value; domain=cookieDomain";
Take Google as an example. To achieve cross-host access, you can write:

document.cookie="name=value;domain=.google.com";
In this way, all hosts under google.com can access the cookie.

Comprehensive example: Constructing a universal cookie processing function
The cookie processing process is relatively complex and has certain similarities. Therefore, several functions can be defined to complete common cookie operations, thereby achieving code reuse. Common cookie operations and their function implementations are listed below.

1. Add a cookie: addCookie(name, value, expiresHours)
This function receives 3 parameters: cookie name, cookie value, and how many hours it will expire. It is agreed here that when expiresHours is 0, no expiration time is set, that is, the cookie disappears automatically when the browser is closed. The function is implemented as follows:
Copy code The code is as follows:



2. Get the cookie value of the specified name: getCookie(name)
This function returns the cookie value named name. If it does not exist, it returns empty. Its implementation is as follows:
Copy code The code is as follows:



3. Delete the cookie with the specified name: deleteCookie(name)
This function can delete the cookie with the specified name. Its implementation is as follows:
Copy code The code is as follows:


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