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. < The requirement for value > 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 쿠키를 삭제하려고 합니다.
expires .setTime(expires.getTime() - 1); document.cookie = 'name=rose;expires='expires.toGMTString();
보시다시피 날짜를 현재 날짜보다 조금 더 빠르게 변경하고(여기서는 1밀리초 더 빠릅니다) 동일한 방법을 사용하여 쿠키를 설정하면 쿠키를 삭제할 수 있습니다.