Js read write delete Cookie code sharing and detailed comments

  • 2020-03-30 03:10:54
  • OfStack

//It has been verified
// JavaScript Document
//Set cache: setCookie("name",value);
//Var name=getCookie("name");
//DelCookie ("name");
/// set a cookie
function setCookie(NameOfCookie, value, expiredays)
 //@ parameter: three variables are used to set the new cookie:
 //The name of the cookie, the stored cookie value,
 //And the time that the Cookie expired.
 //These lines convert days to valid dates
 var ExpireDate = new Date ();
 ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
 //The following line is used to store cookies, simply assign a value to "document.cookie".
 //Notice that the date is converted toGMT time via the toGMTstring() function.
 document.cookie = NameOfCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
/// gets the cookie value
function getCookie(NameOfCookie)
 //First let's check to see if the cookie exists.
 //The length of the document.cookie is 0 if it does not exist
 if (document.cookie.length > 0)
  //Then we check to see if the name of the cookie exists in document.cookie
  //Since more than one cookie value is stored, even if the length of the document.cookie is not 0, there is no guarantee that the cookie with the desired name will exist
  //So we need this step to see if we have the cookie that we want
  //If begin's variable is worth -1, it doesn't exist
  begin = document.cookie.indexOf(NameOfCookie+"=");
  if (begin != -1)   
   //Indicates that our cookie exists.
   begin += NameOfCookie.length+1;//The initial location of the cookie value
   end = document.cookie.indexOf(";", begin);//End position
   if (end == -1) end = document.cookie.length;// There is no ; the end As a string End position
   return unescape(document.cookie.substring(begin, end));
 return null;
 //The cookie does not exist and returns null
/// delete cookies
function delCookie (NameOfCookie)
 //This function checks whether the cookie is set, and if so, sets the expiration time to the past time.
 //The operating system is left to clean up the cookies at the appropriate time
 if (getCookie(NameOfCookie))
  document.cookie = NameOfCookie + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";

Related articles: