javascript Operation cookie

  • 2021-07-12 04:52:57
  • OfStack

Use of front-end js cookie

The role of cookie: The server can use the arbitrariness of the information contained in Cookies to filter and regularly maintain this information to determine the status in HTTP transmission. The most typical application of Cookies is to determine whether the registered user has logged into the website, and the user may be prompted whether to keep the user information on the next visit to this website to simplify the login procedures. These are the functions of Cookies. Another important application is processing such as "shopping cart". Users may choose different products on different pages of the same website for a period of time, and this information will be written into Cookies, so that the information can be extracted at the time of final payment.

js Set cookie

document.cookie="popped=yes"

js Get cookie


function get_cookie(Name) {
  var search = Name + "="// Query retrieved values 
  var returnvalue = "";// Return value 
  if (document.cookie.length > 0) {
   sd = document.cookie.indexOf(search);
   if (sd!= -1) {
    sd += search.length;
    end = document.cookie.indexOf(";", sd);
    if (end == -1)
     end = document.cookie.length;
     //unescape()  Function can be used to pass the  escape()  The encoded string is decoded. 
    returnvalue=unescape(document.cookie.substring(sd, end))
   }
  } 
  return returnvalue;
}
// Usage: 
get_cookie("popped");

Set the end date for cookie

For example, if you want to set cookie to expire after 10 days, you can do this:


// Get the current time 
var date=new Date();
var expiresDays=10;
// Will date Set to 10 Days from now 
date.setTime(date.getTime()+expiresDays*24*3600*1000);
// Will userId And userName Two cookie Set to 10 Expired in days 
document.cookie="userId=828; userName=hulk; expires="+date.toGMTString();

Delete cookie

To delete an cookie, you can set its expiration time to 1 past time, for example:


// Get the current time 
var date=new Date();
// Will date Set to past time 
date.setTime(date.getTime()-10000);
// Will userId This cookie Delete 
document.cookie="userId=828; expires="+date.toGMTString();

The method above is encapsulated below


var cookie = {
  set:function(key,val,time){// Settings cookie Method 
    var date=new Date(); // Get the current time 
    var expiresDays=time; // Will date Set to n Days from now 
    date.setTime(date.getTime()+expiresDays*24*3600*1000); // Formatted as cookie Time of recognition 
    document.cookie=key + "=" + val +";expires="+date.toGMTString(); // Settings cookie
  },
  get:function(key){// Get cookie Method 
    /* Get cookie Parameter */
    var getCookie = document.cookie.replace(/[ ]/g,""); // Get cookie And will get the cookie Format, remove space characters 
    var arrCookie = getCookie.split(";") // What will be obtained cookie With " Semicolon " For the identity   Will cookie Save to arrCookie In the array of 
    var tips; // Declare variables tips
    for(var i=0;i<arrCookie.length;i++){  // Use for Loop lookup cookie In tips Variable 
      var arr=arrCookie[i].split("=");  // Will be single cookie Use " Equal sign " For identification, a single cookie Save as arr Array 
      if(key==arr[0]){ // Matches the variable name, where arr[0] Refers to cookie Name, if the variable is tips The assignment operation in the decision statement is performed 
        tips=arr[1];  // Will cookie Assign the value of to the variable tips
        break;  // Terminate for Cyclic traversal 
      }
    },
   delete:function(key){ // Delete cookie Method 
     var date = new Date(); // Get the current time 
     date.setTime(date.getTime()-10000); // Will date Set to past time 
     document.cookie = key + "=v; expires =" +date.toGMTString();// Settings cookie
    }
    return tips;
  }
}

Usage:


cookie.set("uesr","sss",24);// Set to 24 Expired in days 
alert(cookie.get("uesr"));// Get cookie

Related articles: