Home  >  Article  >  Web Front-end  >  JavaScript implements cookie writing, reading, and deletion functions_javascript skills

JavaScript implements cookie writing, reading, and deletion functions_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:33:471136browse

Before introducing the main text, let me first introduce you to the basic knowledge of Cookie

First understand what cookies are

 "A cookie is a variable that is stored on the visitor's computer. This cookie is sent each time the same computer requests a page through a browser. You can use JavaScript to create and retrieve the cookie's value."

A cookie is a file created by a visited website to store browsing information, such as profile information.

From a JavaScript perspective, cookies are 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 a size limit. The data stored in each cookie cannot exceed 4kb. If the length of the cookie string exceeds 4kb, this attribute 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 an expiration date. 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.

The result of alert(typeof document.cookie) is string. I once thought it was array, and I even made a joke...囧

Cookies have the concept of domain and path. Domain is the concept of domain. Because the browser is a security 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

Third-party cookies from other domain sources such as embedded ads or images 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 be roughly divided into two states:

Temporary cookies. The website will store some of your personal information during current use, and this information will also be deleted from your computer when the browser is closed
Set the cookie with expiration time. 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. Such cookies 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, and the browser itself also has this function)
Clear cookies by setting their expiry date

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^_^.

This chapter shares a few paragraphs about simple operations of JavaScript on cookies, such as writing and deleting cookies.

The code is very simple and is more suitable for reference by friends who are not familiar with basic cookie operations.

1. Write cookie:

//两个参数,一个是cookie的名子,一个是值
function SetCookie(name,value){
 var Days = 30;//此 cookie 将被保存 30 天
 var exp = new Date();//new Date("December 31, 9998");
 exp.setTime(exp.getTime() + Days*24*60*60*1000);
 document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

2. Read cookies:

//取cookies函数  
function getCookie(name){
 var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
 if (arr != null) return unescape(arr[2]); return null;
}

3. Delete cookies:

//删除cookie
function delCookie(name){
 var exp = new Date();
 exp.setTime(exp.getTime() - 1);
 var cval = getCookie(name);
 if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
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