Home Web Front-end JS Tutorial JavaScript implements cookie writing, reading, and deletion functions_javascript skills

JavaScript implements cookie writing, reading, and deletion functions_javascript skills

May 16, 2016 pm 03:33 PM

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: =; 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();
}
Copy after login

2. Read cookies:

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

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();
}
Copy after login
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles