SoFunction
Updated on 2025-04-07

JavaScript encapsulation Cookie application interface

This article records some things I understand when reading cookies, deepens my memory and organizes them to facilitate subsequent review.

Encapsulation function

Accessing cookies by default is a cumbersome thing. Since cookies store information through character strings, it is easy to cause the data type that needs to be converted to the read information when performing assignment operations. Moreover, the string of cookie information is annoying in itself, which is particularly inconvenient in web applications that often use cookie information. Therefore, you need to encapsulate a cookie function yourself to provide development efficiency!

Define a function Cookie(). This function can write the specified cookie information, delete the specified cookie information, and read the cookie value of the specified name. In addition, the validity period, effective path, scope and security option settings of the cookie information can also be set in this function. Complete code:

var Cookie = function(name, value, options) {
    // If the second parameter exists    if (typeof value != 'undefined') {
      options = options || {};
      if (value === null) {
        // Set the expiration time         = -1;
      }
      var expires = '';
      // If there is an event parameter item and the type is number, or the specific time, then set the event separately      if ( && (typeof  == 'number' || )) {
        var date;
        if (typeof  == 'number') {
          date = new Date();
          (() + ( * 24 * 60 * 60 * 1000));
        } else {
          date = ;
        }
        expires = '; expires=' + ();
      }
      var path =  ? '; path=' +  : '', // Set path        domain =  ? '; domain=' +  : '', // Set the domain        secure =  ? '; secure' : ''; // Set security measures, if true, set directly, otherwise it will be empty
      // Save all string information into an array, then call the join() method to convert it into a string, and write cookie information       = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); 
    } else { // If the second parameter does not exist      var CookieValue = null;
      if ( &&  != '') {
        var Cookie = (';');
        for (var i = 0; i < ; i++) {
          var Cookie = (Cookie[i] || "").replace( /^\s+|\s+$/g, "");
          if ((0,  + 1) == (name + '=')) {
            CookieValue = decodeURIComponent(( + 1));
            break;
          }
        }
      }
      return CookieValue;
    }
  };

How to use

Write cookie information:

// Simply write a cookie messagecookie("user", "baidu");
// Write a cookie message and set more optionscookie("user", "baidu", {
  expires: 10, // Valid for 10 days  path: "/", // The entire site is valid  domain: "", // Valid domain name  secure: true // Encrypted data transmission});

2. Read cookie information:

cookie("user");

3. Delete cookie information:

cookie("user", null);

I'll share with you a packaged code

//Write data to cookiesfunction writeCookie(name, value, days) {
 // Define the valid date (the validity time of the cookie) var expires = "";

 // Assign a value to the valid date if (days) {
  var date = new Date();
	//Set the validity period (current time + time period)  (() + (days * 24 * 60 * 60 * 1000));//Time period is milliseconds  expires = "; expires=" + ();
 }

 // Assign a value to the cookie name, value and expiration date (valid period)  = name + "=" + value + expires + "; path=/";
}
//Read cookie datafunction readCookie(name) {
 var searchName = name + "=";
 var cookies = (';');
 for(var i=0; i < ; i++) {
  var c = cookies[i];
  while ((0) == ' ')
   c = (1, );
  if ((searchName) == 0)
   return (, );
 }
 return null;
}
//Clear all cookiesfunction eraseCookie(name) {
 // Set time to -1 to clear data stored in cookies writeCookie(name, "", -1);
}

Finally, if there are any errors and questions in the article, please point them out. Let me share with you all!