javascript operation Cookie (set read delete) method

  • 2020-05-16 06:24:16
  • OfStack

Cookie is a way for clients to store data, which can be used to maintain state.

1. Set Cookie:

a. No expiration time :(if you do not set the expiration time, the default is session-level Cookie, and the browser will be disabled if closed)


function setCookie(name,value) {
    document.cookie = name + '=' + escape(value);
}

b. Fixed expiration time:


function setCookie(name,value)
{
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

c. Custom expiration time:


// Set a custom expiration time cookie
function setCookie(name,value,time)
{
    var msec = getMsec(time); // For ms
    var exp = new Date();
    exp.setTime(exp.getTime() + msec*1);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
// Converts the string time to milliseconds ,1 seconds =1000 ms
function getMsec(DateStr)
{
   var timeNum=str.substring(0,str.length-1)*1; // Number of time
   var timeStr=str.substring(str.length-1,str.length); // Time unit prefix, such as h Said hours
  
   if (timeStr=="s") //20s said 20 seconds
   {
        return timeNum*1000;
   }
   else if (timeStr=="h") //12h said 12 hours
   {
       return timeNum*60*60*1000;
   }
   else if (timeStr=="d")
   {
       return timeNum*24*60*60*1000; //30d said 30 day
   }
}

2. Read Cookie:


function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); // Regular match
    if(arr=document.cookie.match(reg)){
      return unescape(arr[2]);
    }
    else{
     return null;
    }
}

3. Delete Cookie:


function delCookie(name)
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null){
      document.cookie= name + "="+cval+";expires="+exp.toGMTString();
    }
}

4. Call example:


setCookie("name","hayden");
alert(getCookie("name"));

The above is the article about javascript operation cookie all content, hope to be able to help you learn javascript.


Related articles: