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.

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('=');
if(arr2[0] == 'age'){
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 = 'username=abc;expires='+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 = 'username=abc;expires='+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('username');
var oLogin = document.getElementById('login');
var oDel = document.getElementById('del');
//判断用户是否曾经登录过
if(getCookie('username')){
oUsername.value = getCookie('username');
}
//定义一个函数来获取指定名称的cookie值:
function getCookie(key){
var arr1 = document.cookie.split(';');
for(var i = 0; i < arr1.length; i++){
var arr2 = arr1[i].split('=');
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+'='+escape(value)+';expires='+oDate.toGMTString();
}
//定义一个函数移除cookie
function removeCookie(key){
setCookie(key,'',-1);
}
oLogin.onclick = function(){
alert('登录成功');
//将输入的用户名存储在cookie中,且在登录5天后cookie过期
setCookie('username',oUsername.value,5);
}
oDel.onclick = function(){
removeCookie('username');
oUsername.value = '';//移除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).

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!
JavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AMJavaScript'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 CasesApr 18, 2025 am 12:19 AMThe 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.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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






