Cookie Overview
If an immutable framework is used to store shopping column data, and the product display page is constantly changing, although this can achieve a function of simulating global variables, it is not rigorous. For example, if you right-click in 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.
A cookie is a mechanism provided by the browser that 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: [email protected] .
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 area 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. Customize the page. If the website provides the function of changing skin or 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 categories:
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 split separated by spaces (;), for example:
document.cookie=”userId=828; userName=hulk”;
Semicolons (;), commas (,), and equal signs (=) cannot be used in cookie names or values. and spaces. 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:
document.cookie="str="+escape("I love ajax");
Equivalent to:
document.cookie="str=I%20love%20ajax";
When using escape() encoding, it is required after retrieving the value Use unescape() to decode 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:
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:
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 will change the cookie named userId The value is set to 929.
Get the value of cookie
The following describes how to get the value of cookie. The value of the cookie can be obtained directly from document.cookie:
var strCookie=document.cookie;
This will obtain a string consisting of multiple name/value pairs separated by semicolons. These name/value pairs include the names under the domain name. All cookies.
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; expires=GMT_String”;
Among them, GMT_String is a time string expressed in GMT format. This statement sets the userId cookie to the expiration time represented by GMT_String. After this time, the cookie will disappear and become inaccessible.
Deleting cookies
To delete a cookie, you can set its expiration time to a time in the past.
Specify the path where the cookie can be accessed. By default, if a cookie is created on a page, the cookie is also accessible to 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 directory 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 represents the directory where cookies can be accessed. 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:
document.cookie="userId=320; path=/";
Specifying the host name that can access the cookie
is similar to the path. The host name refers to the same Different hosts under one domain, for example:
www.google.com and gmail.google.com are two different host names. By default, cookies created on one host cannot be accessed on another host, but they can be controlled through the domain parameter. The syntax format is:
document.cookie="name=value; domain=cookieDomain" ";
Taking 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 general cookie handling function
The cookie processing process is relatively complex and has certain similarities. Therefore, several functions can be defined to complete common operations of cookies, thereby achieving code reuse. Commonly used cookie operations and their function implementations are listed below.
1. Set COOKIES
function SetCookie(name,value,expires,path,domain,secure)
{
var expDays = expires*24*60*60*1000;
var expDate = new Date();
expDate.setTime(expDate.getTime()+expDays);
var expString = ((expires==null) ? “” : (”;expires="+expDate.toGMTString()))
var pathString = ((path==null) ? "" : (";path="+path))
var domainString = ((domain==null) ? “” : (”;domain="+domain))
var secureString = ((secure==true) ? “;secure” : “” )
document.cookie = name + “=" + escape(value) + expString + pathString + domainString + secureString;
}
2. Get the cookie value of the specified name:
function GetCookie(name)
{
var result = null;
var myCookie = document.cookie + ";";
var searchName = name + "=";
var startOfCookie = myCookie.indexOf(searchName);
var endOfCookie;
if (startOfCookie != -1)
{
startOfCookie += searchName.length;
endOfCookie = myCookie.indexOf(";",startOfCookie);
result = unescape(myCookie.substring(startOfCookie, endOfCookie));
}
return result;
}
3. Delete the cookie with the specified name:
function ClearCookie(name)
{
var ThreeDays=3*24*60*60*1000;
var expDate = new Date();
expDate.setTime(expDate.getTime()-ThreeDays);
document.cookie=name+”=;expires=”+expDate.toGMTString();
}