search
HomeWeb Front-endJS TutorialOrganize the application of cookie operation objects in JavaScript

This article brings you relevant knowledge about javascript, which mainly introduces issues related to the application of cookie operation objects. Cookies provide a useful way for Web applications to save user-related information. Let’s take a look at the method below, I hope it will be helpful to everyone.

Organize the application of cookie operation objects in JavaScript

[Related recommendations: javascript video tutorial, web front-end

How to operate cookies in Javascript

Cookies provide a useful way for Web applications to save user-related information. For example, when a user visits our site, cookies can be used to save user preferences or other information so that the next time the user visits our site, the application can retrieve the previously saved information.

What the heck is a cookie

A cookie is a small piece of text information that is passed between the web server and the browser along with user requests and pages. The information contained in the cookie can be read by the web application each time the user visits the site.

Cookies appear to solve the problem of saving user information. For example

  • When a user visits a web page, the user's name can be stored in a cookie.

  • The cookie will remember the username the next time the user visits the page.

Cookies can remember user information across all web pages. It contains information in the form of a string and is saved in the form of key-value pairs, that is, in the key=value format. Each cookie is usually separated by ";".

username = Daisy Green

Cookie Disadvantages

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;

Cookies are related to the browser. This means that even if you visit the same page, cookies saved by different browsers cannot be accessed by each other;

cookies may be deleted. Because each cookie is a file on the hard disk, it is likely to be deleted by the user;

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.

How Cooke works

The server sends some data to the visitor's browser in the form of a cookie. If your browser allows cookies to be accepted. It is stored on the visitor's hard drive as a plain text record.

When a visitor jumps to another page, the browser will send the same cookie to the server for retrieval. Once it is retrieved, your server knows or remembers what was previously stored.

Composition of Cookie

Cookie In the HTTP header information, the header format of HTTP Set-Cookie is as follows:

Set-Cookie: name=value; [expires=date]; [path=path];
[domain=domainname]; [secure];

In the HTTP code A specific example:

<meta http-equiv="set-cookie" content=" cookieName = cookieValue;
expires=01-Dec-2006 01:14:26 GMT; path=/" />

As can be seen from the above format, Cookie consists of the following parts.

Name/Value pair

Name/Value is separated by a semicolon. A cookie can have up to 20 pairs. Each web page can have at most one cookie. The length of Value should not exceed 4K. For Value values, it is best to encode them with encodeURIComponent.

Domain

Domain domain name is also part of the cookie. By default, the domain name of the web page visited by the user will be stored in the cookie. If the domain name value of this cookie is set, it means that all servers on the domain name, not just the server you are visiting, can access this cookie. Generally, you should not do this. The format of setting the domain name is as follows: domain=http://xyz.com

path

Set the web pages in which directory for a specific server to access cookies. The format of setting the path is: path = /movies

Expires

Set the cookie survival time. By default, the cookie is automatically deleted when the user closes the browser. If not Set the cookie expiration time so that the cookie disappears when the user closes the browser. If you set this item, you can extend the cookie life. Set the time in js using the GMT form of the Date object. The format is as follows: expires = date.toGMTString()

Secure

Take the true or false value. If true, the cookie must be sent over https.

In JS, you can use the cookie attribute of the Document object to manipulate cookies. JS can read, create, modify and delete the cookies of the current web page. Let’s take a look at the specific operations.

Create Cookie

JS can use the document.cookie attribute to create a cookie. You can create a cookie in the following ways:

document.cookie = "username=Daisy Green";

You can also add a valid date ( UTC time). By default, cookies are deleted when the browser is closed:

document.cookie = "username=Daisy Green; expires=Mon, 26 Aug 2019 12:00:00 UTC";

Through the path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

document.cookie = "username=Daisy Green; expires=Mon, 26 Aug 2019 12:00:00 UTC"; path=/";

Read Cookie

Through JS, you can read cookies like this:

var x = document.cookie;

document.cookie 会在一条字符串中返回所有 cookie,比如:cookie1=value; cookie2

事例:

<html>
   <head>   
      <script type = "text/JavaScript">
         <!--
            function ReadCookie() {
               var allcookies = document.cookie;
               document.write ("All Cookies : " + allcookies );
                
               // Get all the cookies pairs in an array
               cookiearray = allcookies.split(&#39;;&#39;);
                
               // Now take key value pair out of this array
               for(var i=0; i<cookiearray.length; i++) {
                  name = cookiearray[i].split(&#39;=&#39;)[0];
                  value = cookiearray[i].split(&#39;=&#39;)[1];
                  document.write ("Key is : " + name + " and Value is : " + value);
               }
            }
         //-->
      </script>      
   </head>
    
   <body>     
      <form name = "myform" action = "">
         <p> click the Button to View Result:</p>
         <input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
      </form>      
   </body>
</html>

改变 cookie

通过使用 JS,咱们可以像创建 cookie 一样改变它:

document.cookie = "username=Steve Jobs; expires=Sun, 31 Dec 2017 12:00:00 UTC; path=/";

这样旧 cookie 会被覆盖。

事例:

<html>
   <head>   
      <script type = "text/JavaScript">
         <!--
            function WriteCookie() {
               var now = new Date();
               now.setMonth( now.getMonth() + 1 );
               cookievalue = escape(document.myform.customer.value) + ";"
                
               document.cookie = "name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>      
   </head>
    
   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>      
   </body>
</html>

删除 cookie

删除 cookie 非常简单,不必指定 cookie 值:直接把 expires 参数设置为过去的日期即可:

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

应该定义 cookie 路径以确保删除正确的 cookie。如果不指定路径,有些浏览器不会让咱们删除 cookie。

事例:

<html>
   <head>   
      <script type = "text/javascript">
         <!--
            function WriteCookie() {
               var now = new Date();
               now.setMonth( now.getMonth() - 1 );
               cookievalue = escape(document.myform.customer.value) + ";"
                
               document.cookie = "name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write("Setting Cookies : " + "name=" + cookievalue );
            }
          //-->
      </script>      
   </head>
    
   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>      
   </body>
</html>

【相关推荐:javascript视频教程web前端

The above is the detailed content of Organize the application of cookie operation objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!