search
HomeWeb Front-endJS TutorialHow to implement cookie operation in javascript

Method: 1. Use the "document.cookie="name=value;"" statement to set the cookie or modify the cookie value; 2. Use the "document.cookie" statement to obtain the cookie value; 3. Pass the valid The time "expires" is set to the expiration value to delete the cookie.

How to implement cookie operation in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Cookies are variables stored on a visitor's computer. When a user visits a website, data can be stored on the visitor's computer through cookies. Later, when the user requests the page again through the browser on the same computer, this cookie is sent and the cookie can be used to identify the user.

1. Setting cookies

Using cookies to store data is achieved by setting cookies. Each cookie is a name/value pair. The name/value pairs are connected with an equal sign, and the name/value pair is assigned to document.cookie. Multiple name/value pairs can be assigned to document.cookie at one time, using semicolons and spaces to separate each name/value pair.

The basic format of setting cookies is as follows:

document.cookie = "名称1=值1[; 名称2=值2; …]";

The example of setting cookies is as follows:

document.cookie = "username=abc";
document.cookie = "age=23";
document.cookie = "username=abc; age=23";

It should be noted that semicolons cannot be used in the name or value of cookies; and equal sign = equal sign. If you want to store these symbols, you need to use the escape() function for encoding. For example: document.cookie="str=" escape("username=nch"), this code is equivalent to: document.cookie="str=username=nch", that is, the equal sign is encoded as =. When using escape() encoding, you need to use unescape() to decode after taking out the value to get the original cookie value.

In addition, when the value in the cookie set using the above format is stored in the user's computer, the data of different websites is distinguished in the form of website domain name, and different browsers store cookies in different locations, so different browsing Cookies stored between servers cannot be accessed by each other. In addition, there is a limit to the number of cookies stored under the same domain name, and different browsers have different limits on the number of cookies stored. Moreover, the size of the content stored in each cookie is also limited, and different browsers have different size limits.

2. Modify cookie value

If you want to change a cookie value, just reassign it, for example: document.cookie="age=36 ";This way you can modify the cookie value of age=23 set previously.

3. Get cookie

When you get the cookie under the current website through document.cookie, you get the value in the form of a string. This value contains all cookies under the current website. It will concatenate all cookies through a semicolon and a space.

To obtain different cookie values, you can use the split() method to convert the string containing semicolons and spaces into a string array separated by semicolons, and then traverse the string array. Each name/value pair can be obtained. Use the split() method again to convert this name/value pair into an array containing names and values ​​separated by equal signs, and you can get the value of the specified cookie name.

For example, the code to get the value of cookie named age is as follows:

document.cookie = "username=abc; age=23";
var arr1 = document.cookie.split(';');
for(var i = 0; i < arr1.length; i++){
     var arr2 = arr1[i].split(&#39;=&#39;);
     if(arr2[0] == &#39;age&#39;){
         alert(arr2[1]);
     }
}

4. Set the validity time of cookie

By default, cookie It is temporarily stored, that is, it is stored in memory by default and is not stored on the hard disk, so the stored cookie will be automatically destroyed after the browser process is closed. If you want to save cookies in your computer for a period of time or permanently, you need to set a valid time when setting the cookie. The setting format is as follows:

document.cookie = "名称=值;expires="+字符串格式的时间;

For example:

var oDate = new Date();
oDate.setDate(oDate.getDate()+10);//访问页面后的10天过期
//设置cookie的有效时间,时间为字符串格式
document.cookie = &#39;username=abc;expires=&#39;+oDate.toGMTString();

5. Delete the cookie

and directly set the validity time of the cookie to a certain time in the past. For example:

var oDate = new Date();
oDate.setDate(oDate.getDate()-1);//访问页面的前一天
document.cookie = &#39;username=abc;expires=&#39;+oDate.toGMTString();

[Example 1] Use document to operate cookies.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>使用cookie记住登录用户名</title>
<script>
     window.onload = function(){
         var oUsername = document.getElementById(&#39;username&#39;);
         var oLogin = document.getElementById(&#39;login&#39;);
         var oDel = document.getElementById(&#39;del&#39;);
         //判断用户是否曾经登录过
         if(getCookie(&#39;username&#39;)){
              oUsername.value = getCookie(&#39;username&#39;);
         }
         //定义一个函数来获取指定名称的cookie值:
         function getCookie(key){
              var arr1 = document.cookie.split(&#39;;&#39;);
              for(var i = 0; i < arr1.length; i++){
                  var arr2 = arr1[i].split(&#39;=&#39;);
                  if(arr2[0] == key){
                       return unescape(arr2[1]);//对编码后的内容进行解码
                  }           
              }
         }    
         //定义一个函数来设置cookie,同时设置cookie的有效时间
         function setCookie(key,value,t){
              var oDate = new Date();
              oDate.setDate(oDate.getDate()+t);
              //使用escape()对内容进行编码
              document.cookie = key+&#39;=&#39;+escape(value)+&#39;;expires=&#39;+oDate.toGMTString();         
         }    
         //定义一个函数移除cookie
         function removeCookie(key){
              setCookie(key,&#39;&#39;,-1);
         }
         oLogin.onclick = function(){
              alert(&#39;登录成功&#39;);
              //将输入的用户名存储在cookie中,且在登录5天后cookie过期
              setCookie(&#39;username&#39;,oUsername.value,5);
         }
         oDel.onclick = function(){
              removeCookie(&#39;username&#39;);
              oUsername.value = &#39;&#39;;//移除cookie后清空文本框内容
         }
     };
</script>
</head>
<body>
     <input type="text" id="username"/>
     <input type="button" value="登录" id="login"/>
     <input type="button" value="删除用户名cookie" id="del"/>
</body>
</html>

Note: Firefox and IE only allow temporary operation of cookies locally, and cookies cannot be obtained after closing the browser. Chrome, on the other hand, does not allow local manipulation of cookies. When Example 1 is published to a Web server and then accessed, these browsers can manipulate cookies.

The following figure shows the results of accessing and publishing to the Tomcat Web server in the Chrome browser and clicking the login button and delete button after entering the user name (the Tomcat server is on this machine, so you can use localhost as the domain name to access it).

How to implement cookie operation in javascript

How to implement cookie operation in javascript

Enter the username and click the login button. Close the Chrome browser before clicking the delete username cookie button. process, and then open Chrome again to access Example 1, you can get the result shown in Figure 3, that is, the user name will be automatically displayed in the text box. If you click the delete username cookie button, close the Chrome browser process, and then open Chrome again to access Example 1, you will get the result shown in Figure 4. At this time, the username stored in the cookie has been deleted and cannot be displayed. text box.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to implement cookie operation in javascript. For more information, please follow other related articles on the PHP Chinese website!

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

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version