Detailed analysis of the use of cookies in js_javascript skills
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:
document.cookie="str= " escape("I love ajax");
is equivalent to:
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:
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 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:
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:
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:
Delete cookie
In order to delete a cookie, you can set its expiration time to a time in the past, for example:
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:
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:
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:
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:

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Many Windows users have recently encountered an unusual error called Roblox403 Forbidden Error while trying to access website URLs in Google Chrome browser. Even after restarting the Chrome app multiple times, they were unable to do anything. There could be several potential causes for this error, some of which we've outlined and listed below. Browsing history and other cache of Chrome and corrupted data Unstable internet connection Incorrect website URLs Extensions installed from third-party sources After considering all the above aspects, we have come up with some fixes that can help users resolve this issue. If you encounter the same problem, check out the solutions in this article. Fix 1

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

The working principle of cookies involves the server sending cookies, the browser storing cookies, and the browser processing and storing cookies. Detailed introduction: 1. The server sends a cookie, and the server sends an HTTP response header containing the cookie to the browser. This cookie contains some information, such as the user's identity authentication, preferences, or shopping cart contents. After the browser receives this cookie, it will be stored on the user's computer; 2. The browser stores cookies, etc.

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

The effects of clearing cookies include resetting personalization settings and preferences, affecting ad experience, and destroying login status and password remembering functions. Detailed introduction: 1. Reset personalized settings and preferences. If cookies are cleared, the shopping cart will be reset to empty and products need to be re-added. Clearing cookies will also cause the login status on social media platforms to be lost, requiring re-adding. Enter your username and password; 2. It affects the advertising experience. If cookies are cleared, the website will not be able to understand our interests and preferences, and will display irrelevant ads, etc.

The dangers of cookie leakage include theft of personal identity information, tracking of personal online behavior, and account theft. Detailed introduction: 1. Personal identity information is stolen, such as name, email address, phone number, etc. This information may be used by criminals to carry out identity theft, fraud and other illegal activities; 2. Personal online behavior is tracked and analyzed through cookies With the data in the account, criminals can learn about the user's browsing history, shopping preferences, hobbies, etc.; 3. The account is stolen, bypassing login verification, directly accessing the user's account, etc.
