Processing cookies in JavaScript is complicated because of its well-known interface, namely the doucmentcookie attribute of BOM. This attribute is unique in that it will show different behaviors in different ways. When used to obtain the property value, documentcookie returns a result that processing cookies in JavaScript is complicated because of its well-known interface, namely the doucment. cookie attribute of BOM. This attribute is unique in that it will show different behaviors in different ways. Document. the cookie returns the strings of all cookies available on the current page (based on the cookie's domain, path, expiration time, and security settings). A series of name-value pairs separated by semicolons are as follows:
Name1 = value1; name2 = value2; name3 = value3; 1 all names and values are URL encoded, so decodeURIComponent () must be used for decoding. When used for setting, the document. cookie attribute can be set as a new cookie string. The cookie string is interpreted and added to the existing cookie set. Setting document. cookie does not overwrite the cookie unless the cookie name already exists. The cookie format is as follows, which is the same as that used in the set-Cookie header: name = value; expires = expiration_time; path = domian_path; domian = domain_nam, only the cookie name and value are required. The following is a simple example: document. cookie = "name = Nicklas"; this Code creates a cookie named name with the value of Nicolas. The cookie is sent every time the client sends a request to the server. When the browser is closed, the cookie is deleted. Although this code is okay, it is recommended that you use encodeURIComponent (); document. cookie = encodeURIComponent ("name") + "=" + encodeURIComponent ("Nicklas"); to specify additional information for the created cookie, you only need to append the parameter to this string, the format is the same as that in the Set-Cookie header: document. cookie = encodeURIComponent ("name") + "=" + encodeURIComponent ("Nicklas") + "; domain = .wrox.com; path = /";
Since reading and writing cookies in JavaScript is not very intuitive, we often write some functions to simplify the functions of cookies. There are three basic cookie operations: read, write, and delete. They are represented in the CookieUtil object as follows:
var CookieUtil = { get: function (name) { var cookieName = encodeURIComponent(name) + "=", cookieStart = document.cookie.indexOf(cookieName), cookieValue = null; if (cookieStart > -1) { var cookieEnd = document.cookie.indexOf(";", cookieStart) if (cookieEnd == -1) { cookieEnd = document.cookie.length; } cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd)); } return cookieValue; }, set: function (name, value, expires, path, domain, secure) { var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value); if (expires instanceof Date) { cookieText += "; expires=" + expires.toGMTString(); } if (path) { cookieText += "; path=" + path; } if (domain) { cookieText += "; domain=" + domain; } if (secure) { cookieText += "; secure"; } document.cookie = cookieText; }, unset: function (name, path, domain, secure) { this.set(name, "", new Date(0), path, domain, secure); }};
The CookieUtil. get () method obtains the value based on the cookie name. In the document. cookie string, search for the location where the cookie name is equal to or greater than the cookie name. If so, use indexOf () to find the first semicolon (indicating the end position of the cookie) after the location ). If the semicolon is not found, the cookie is the last one in the string, and the strings in the domain are the cookie values. This value is decoded using decodeURIComponent () and finally returned. If no Cookie is found, null is returned.
CookieUtil. the set () method sets a cookie on the page and accepts the following parameters: cookie name, cookie value, and optional Date object used to specify when the cookie should be deleted, cookie optional URL path, optional domain, and optional Boolean value indicating whether to add the secure flag. Parameters are arranged according to their usage frequency. Only the first two parameters are required. In this method, both names and values use encodeURIComponent () for URL encoding and check other options. If the expires parameter is a Date object, the Date object is correctly formatted using the toGMTString () method of the Date object and added to the expires option. The other part of the method is to construct a cookie string and set it to document. cookie.
There is no direct method to delete existing cookies. Therefore, you need to use the same path, domain, and security options to set the cookie again, and set the expiration time to the past time. The CookieUtil. unset () method can handle such a problem. It accepts four parameters: the name of the cookie to be deleted, optional path parameters, optional domain parameters, and optional security parameters. These parameters are passed to CookieUtil. set () by adding an empty string and setting the expiration time to January 1, 1970 (the value of the Date object initialized to 0 ms (). This ensures that the cookie is deleted.
These methods can be used as follows:
// Set cookieCookieUtil. set ("name", "Nicolas"); CookieUtil. set ("book", "Professional JavaScript"); // read value alert (CookieUtil. get ("name"); alert (CookieUtil. get ("book"); // Delete cookieCookieUtil. unset ("name"); CookieUtil. unset ("book") // sets a cookie, including its path, domain, and end date CookieUtil. set ("name", "Nicolas", "/books/projs/", "www.wrox.com", new Date ("January 1, 2010"); // Delete the same cookieCookieUtil. unset ("name", "/books/projs/", "www.wrox.com"); // sets one secure cookieCookieUtil. set ("name", "Nicolas", null, true );
By processing the parsing and constructing cookie strings, these methods make it easier to store data on the client using cookies.