Examples of cookie object usage in javascript and Analysis of cookie instances
This example describes how to use cookie objects in javascript. Share it with you for your reference. The details are as follows:
Attribute
Unique attribute that must be set for name, indicating the cookie name
Expires specifies the cookie lifecycle. If this parameter is not set, the browser will automatically fail when it is disabled.
Path determines the availability of cookies for other web pages on the server. Generally, cookies are available for all pages in the same directory. After the path attribute is set, cookie is only valid for all webpages in the specified path and sub-Path
Domain many servers are composed of multiple servers. The domain attribute mainly sets multiple servers in the same domain to share a cookie. If web server a needs to share a cookie with web Server B, set the domain attribute of cookie a to B so that the cookie created by a can be shared by a and B.
Secure generally supports SSL websites starting with HTTPS. The secure attribute can be set to cookie, which can only be accessed through HTTPS or other security protocols.
Cookie is essentially a string
Generally, Cookies cannot contain special characters such as semicolons, commas, and spaces. However, these characters can be transmitted using encoding, that is, convert the special characters in the text string to the corresponding hexadecimal ASCII value. You can use the encodeURI () function to convert the text character to a valid URI. Use decodeURI () function Decoding
Write cookie
Var cookieTest = "name = userName"; document. cookie = cookieTest; // save // use a semicolon to separate different attributes var date = newDate (); date. setDate (date. getDate () + 7); // set the cookie survival time to a week document. cookie = encodeURI ("name = user") + "; expires =" + date. toUTCString ();
Read cookie
var cookieString= decodeURI(document.cookie); var cookieArray= cookieString.split(";"); for(vari=0;i< cookieArray.length;i++){ var cookieNum = cookieArray[i].split("="); var cookieName = cookieNum[0]; var cookieValue = cookieNum[1]; }
Delete cookie
Var date = newDate (); date. setTime (date. getTime ()-10000); document. cookie = "name = User; expires =" + date. toGMTString; // when a cookie is deleted, the expiration time is set to a previous time value.
I hope this article will help you design javascript programs.