search
HomeWeb Front-endJS TutorialJavaScript introductory tutorial Cookies_Basic knowledge

Some Web sites store information on your hard drive in small text files called cookies. ” - MSIE Help. Generally speaking, Cookies are created by CGI or similar files, programs, etc. that are more advanced than HTML, but JavaScript also provides very comprehensive access rights to Cookies.
Before continuing, let’s first Learn the basics of Cookie.
Each Cookie is like this: =
The restrictions of are similar to the naming restrictions of JavaScript. There is less "cannot use JavaScript keywords" and more "can only use characters that can be used in URL encoding". The latter is more difficult to understand, but as long as you only use letters and numbers in the name, there is no problem. is also "can only use characters that can be used in URL encoding".
Each cookie has an expiration date. Once the computer's clock passes the expiration date, we cannot delete the cookie. Delete a cookie directly, but you can delete it indirectly by setting the expiration date earlier than the current time.
Each web page, or each site, has its own cookies, which can only be deleted by. Pages from this site, as well as pages from other sites or unauthorized areas of the same site, cannot be accessed. Each "set" of cookies has a specified total size (approximately 2KB per "set") that exceeds one. The maximum total size, the earliest expired Cookie will be deleted first to allow the new Cookie to "settle". Now let's learn to use the document.cookie attribute. If you use the document.cookie attribute directly, or use Some method, such as assigning a value to a variable, to get the value of document.cookie, we can know how many cookies there are in the current document, the name of each cookie, and its value. For example, add "in a document." document.write(document.cookie)", the result shows:


name=kevin; email=kevin@kevin.com; lastvisited=index.html


This means that the document contains 3 Cookies: name, email and lastvisited, and their values ​​are kevin, kevin@kevin.com and index.html. As you can see, the two Cookies are separated by semicolons and spaces, so we can use the cookieString.split('; ') method to get an array of each Cookie (first use var cookieString = document.cookie) .
The way to set a Cookie is to assign a value to document.cookie. Unlike assignment in other cases, assigning a value to document.cookie will not delete the original Cookies, but will only add Cookies or change the original Cookies. Format of assignment:


document.cookie = 'cookieName=' escape('cookieValue')
';expires=' expirationDateObj.toGMTString();


Are you dizzy? The above words that are not in bold should be copied exactly, and the words in bold should be changed according to the actual situation. cookieName represents the name of the cookie, cookieValue represents the value of the cookie, and expirationDateObj represents the date object name that stores the expiration date. If the expiration date does not need to be specified, the second line is not needed. If the expiration date is not specified, the browser defaults to expiration after closing the browser (that is, closing all windows).
Did you see some underlines above? These are the things that should be paid attention to.
First, escape() method: Why must it be used? Because the requirement for the cookie value is "can only use characters that can be used in URL encoding". We know that the "escape()" method encodes the string according to the URL encoding method, then we only need to use an "escape()" method to process the value output to the Cookie, and use "unescape()" to process the value output from the Cookie. The value received is foolproof. And the most common use of these two methods is to deal with Cookies. In fact, setting a Cookie is as simple as "document.cookie = 'cookieName=cookieValue'", but in order to avoid characters that are not allowed to appear in the URL in the cookieValue, it is better to use escape().
Then the semicolon before “expires”: Just notice it. It's the semicolon and nothing else.
Finally, the toGMTString() method: The expiration date of the cookie is set in GMT format. Time in other formats has no effect.
Now let’s do some actual combat. Set a cookie with "name=rose" to expire in 3 months.


Copy code The code is as follows:

varexpires = new Date();
expires.setTime(expires.getTime() 3 * 30 * 24 * 60 * 60 * 1000)
/* 3개월 x 1개월 30일 x 하루 24시간
x 시간당 60분 x 분당 60초 x 초당 1000밀리초*/
document.cookie = 'name=rose;expires='expires.toGMTString(); 🎜>
왜 escape() 메소드를 사용하지 않나요? 이는 rose가 유효한 URL 인코딩 문자열, 즉 'rose' == escape('rose')임을 알고 있기 때문입니다. 일반적으로 쿠키를 설정할 때 escape()를 사용하지 않으면 쿠키를 가져올 때 unescape()를 사용할 필요가 없습니다.
다시 해 보겠습니다. 지정된 쿠키의 값을 찾는 함수를 작성해 보세요.

코드 복사 코드는 다음과 같습니다.
function getCookie(cookieName) {
var cookieString = document.cookie;
var start = cookieString.indexOf(cookieName '=');
// 등호를 추가하는 이유는 일부 쿠키에
//가 동일하지 않도록 하기 위함입니다. 쿠키 값 문자열.
if (start == -1) // 찾을 수 없음
return null;
start = cookieName.length 1
var end = cookieString.indexOf(';', start); >if (end == -1) return unescape(cookieString.substring(start));
return unescape(cookieString.substring(start, end))


함수는 문자열 객체의 몇 가지 메소드를 사용합니다. 기억이 나지 않는다면(너무 잊어버리시나요?) 빨리 확인해 보세요. 이 함수의 모든 if 문에는 else가 포함되지 않습니다. 이는 조건이 true이면 프로그램이 return 문을 실행하기 때문입니다. 함수에서 return을 만나면 연산이 종료되므로 else를 추가하지 않아도 문제가 없습니다. 이 함수는 쿠키를 찾으면 쿠키 값을 반환하고, 그렇지 않으면 "null"을 반환합니다.
이제 방금 설정한 name=rose 쿠키를 삭제하려고 합니다.



코드 복사 코드는 다음과 같습니다.varexpires = new Date()
expires .setTime(expires.getTime() - 1);
document.cookie = 'name=rose;expires='expires.toGMTString();


보시다시피 날짜를 현재 날짜보다 조금 더 빠르게 변경하고(여기서는 1밀리초 더 빠릅니다) 동일한 방법을 사용하여 쿠키를 설정하면 쿠키를 삭제할 수 있습니다.

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

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.

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor