This article describes the usage of cookie objects in JavaScript. Share it for your reference. The details are as follows:
property
name The unique attribute that must be set, indicating the name of the cookie
expires Specifies the survival cycle of the cookie. If not set, the browser shutdown will automatically expire.
path determines the availability of cookies to the server for other web pages. Generally, cookies are available for all pages in the same directory. When the path attribute is set, cookies are only valid for all web pages under the specified path and sub-path.
domain Many servers are composed of multiple servers. The domain attribute mainly sets multiple servers under the same domain to share a cookie. If web server a needs to share cookies with web server b, the domain attribute of a cookie needs to be set to b, so that the cookies created by a can be shared by a and b.
Secure Websites that generally support SSL start with HTTPS. The secure attribute can set the cookie to be accessed only through HTTPS or other security protocols.
Cookies are essentially strings
Generally speaking, cookies cannot contain special characters such as semicolons, commas, spaces, etc., but these characters can be transmitted using encoding, that is, converting special characters in text strings into corresponding hexadecimal ASCII values. The encodeURI() function can be used to convert text characters into effective URIs, and decoded using decodeURI() function.
Write cookies
var cookieTest = "name=userName"; document.cookie= cookieTest; //Save//Segment different attributes with semicolons var date = newDate(); date.setDate(date.getDate()+7); //Set the survival time of the cookie to one week document.cookie= encodeURI("name=user")+";expires="+date.toUTCString();Read cookies
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 cookies
var date = newDate(); date.setTime(date.getTime()-10000); document.cookie= "name=User;expires="+date.toGMTString; //Delete a cookie is to set its expiration time to a past time value
I hope this article will be helpful to everyone's JavaScript programming.