国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
How to read cookies?
How to set cookies?
How to delete cookies?
Some common things to note
Home Web Front-end JS Tutorial How to handle cookies in vanilla JavaScript?

How to handle cookies in vanilla JavaScript?

Jul 15, 2025 am 02:26 AM
cookie

1. When reading cookies, you can get a string through document.cookie and parse it into an object; 2. When setting cookies, you need to assign a value to document.cookie and add expiration time, path and other options; 3. When deleting cookies, you need to set the expired time and ensure clearing through the same path domain name; 4. Notes include not having sensitive information, processing encoding, limiting length and adding security attributes. The full text revolves around the methods and details of native JS operating cookies.

How to handle cookies in vanilla JavaScript?

Handling cookies on web pages is actually a very common task in front-end development, especially when it is necessary to save user status or do some simple local data storage. It is not complicated to operate cookies with native JavaScript (that is, vanilla JS). You only need to understand how the document.cookie API is used.

How to handle cookies in vanilla JavaScript?

How to read cookies?

document.cookie is a string property that returns all cookies on the current page, in the format of a key-value pair with name=value, separated by a semicolon and space.

for example:

How to handle cookies in vanilla JavaScript?
 console.log(document.cookie);
// Output: username=JohnDoe; visited=true

If you want to convert them into objects for easy use, you can write a small function to parse:

 function getCookies() {
  const cookieStr = document.cookie;
  const cookies = {};
  if (!cookieStr) return cookies;

  cookieStr.split('; ').forEach(cookie => {
    const [name, value] = cookie.split('=');
    cookies[name] = decodeURIComponent(value);
  });

  return cookies;
}

This way you can access it through cookies.username .

How to handle cookies in vanilla JavaScript?

How to set cookies?

Setting cookies is also done through the document.cookie attribute. You can assign values directly:

 document.cookie = "username=JohnDoe";

However, we will generally add some options, such as expiration time, path, domain name, etc.:

  • expires: Specify the expiration time (UTC time format)
  • max-age: Survival time in seconds
  • path: Specify which paths can access this cookie, the default is the current path
  • domain: Specify the domain name
  • Secure: Send only under HTTPS
  • samesite: Prevent CSRF attacks

For example:

 document.cookie = "visited=true; max-age=86400; path=/";

The above line of code sets the visited cookie, survives for one day (86400 seconds), and it can be accessed by the entire website.

Note: If you do not set expires or max-age, then this cookie is a "session cookie" and will be cleared after the browser is closed.

How to delete cookies?

In fact, there is no special deletion method, but it is achieved by setting an expired cookie:

 document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";

This way the browser will clear the cookie.

But to ensure that it can be deleted, it is best to bring the original path and domain settings, otherwise it may not be deleted due to different paths.

 document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";

Some common things to note

  • Do not store sensitive information : cookies will be automatically sent with requests, so they are not suitable for placing sensitive data such as passwords and tokens.
  • Note the encoding problem : If there are special characters in the value part, you should first use encodeURIComponent to encode.
  • Length limit : Each cookie should not be too long, and the total size is also browser limit (usually about 4KB).
  • Security settings : If you want to improve security, remember to add Secure and SameSite=Strict/Lax.

Basically that's it. Although many people now use localStorage for client storage, cookies are still very important in handling server sessions, login status, etc. Mastering basic cookie operations is very helpful for front-end and back-end interactions.

The above is the detailed content of How to handle cookies in vanilla JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1488
72
Where are cookies stored? Where are cookies stored? Dec 20, 2023 pm 03:07 PM

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.

Where are the cookies on your computer? Where are the cookies on your computer? Dec 22, 2023 pm 03:46 PM

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.

How cookies work How cookies work Sep 20, 2023 pm 05:57 PM

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.

What are the dangers of cookie leakage? What are the dangers of cookie leakage? Sep 20, 2023 pm 05:53 PM

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.

Where are the mobile cookies? Where are the mobile cookies? Dec 22, 2023 pm 03:40 PM

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.

How to solve the problem that document.cookie cannot be obtained How to solve the problem that document.cookie cannot be obtained Nov 23, 2023 am 10:02 AM

Solutions for document.cookie not being obtained: 1. Browser privacy settings; 2. Same-origin policy; 3. HTTPOnly Cookie; 4. JavaScript code error; 5. Cookie does not exist or expires; 6. Cross-domain issues; 7. Viewer mode; 8. Server problems; 9. JavaScript execution timing; 10. Check console log, etc.

Does clearing cookies have any impact? Does clearing cookies have any impact? Sep 20, 2023 pm 06:01 PM

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.

How to find cookies in your browser How to find cookies in your browser Jan 19, 2024 am 09:46 AM

In our daily use of computers and the Internet, we are often exposed to cookies. A cookie is a small text file that saves records of our visits to the website, preferences and other information. This information may be used by the website to better serve us. But sometimes, we need to find cookie information to find the content we want. So how do we find cookies in the browser? First, we need to understand where the cookie exists. in browser

See all articles