Set and use JavaScript cookies

Advertising

Last Updated : |  

We can use JavaScript to set, read, update and remove cookies. The special thing is that we are on the client side and so much more than server-side of the user received. So in understandable language we're closer to the user because we're in his browser with our code.



Data protection basic regulation

Take note of the GDPR and inquire what is necessary for you, it depends on what you do for a website.



We create our functions for faster access to everything. I'll turn it into a class later and not just leave it as a function. So let's start and create setMyCookie()with which we will create our cookies and this is quite simple. Here, of course, any tests are missing so that mistakes are avoided, but more in the class below.


// JS CODE
     0  /**  1   * Set the cookie  2   *  3   * @param {array} args  4   */  5   function setMyCookie(args) {  6        document.cookie = args.name + args.expires + args.path + args.domain;  7   } 

    In this function we can now send in our arguments and our cookie will be set. We do this with an object that we call the function as args and divide it into its parts. And here's the following args object:


    // JS CODE
       0  // Get a date object  1  let d = new Date(), args = {};  2  // Set expiry time, here 365 days  3  d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));  4  // Then our object for setMyCookie  5  args = {  6      name: "Visitor=" + JSON.stringify({  7          totalvisits: 0,  8          sites: {}  9      }) + ';',  10      expires: "expires=" + d.toUTCString() + ';',  11      path: 'path=/;',  12      domain: 'domain=localhost;'  13  };  14    15  // Call our function  16  setMyCookie(args); 

      If our cookie has been successfully set, we can read it out, but before we read it out, we will build a checking function to make sure that this cookie exists.



      We check quite simple, if our cookie name exists, this is the case or not, so we can act the corresponding. So we create a new function

      hasMyCookie()
      // JS CODE
         0  /**  1   * Check if the cookie exists  2   *  3   * @param {string} name  4   *  5   * @returns {bool}  6   */  7  function hasMyCookie(name) {  8      return document.cookie.search(name) !== -1 ? true : false;  9  } 

        You can also check if the user allows cookies. So now we can check in advance whether cookies are available or in between.


        navigator.cookieEnabled

        To read the cookie correctly, decode like the cookie and remove our cookie name. Then we transform our string (the object we mentioned above JSON.stringify() have converted to a string) again with an object JSON.parse() So we can access everything in our cookie again, because the way we created it, we also read it out. And again we create a new function that looks like this getMyCookie()


        // JS CODE
           0  /**  1   * Get the cookie  2   *  3   * @param {string} name  4   *  5   * @returns {string}  6   */  7  function getMyCookie(name) {  8      return JSON.parse(decodeURIComponent(document.cookie).replace(name + "=", ''));  9  } 

          This is what the content looks like in JavaScript and you can extend it even further.


          // OUTPUT CODE
          {totalvisits: 2, 
              sites: 
                  index: 
                      hits: 1 
                      url: "Sites/NetBeans/PHP-Cookie/index.php" 
                  second: 
                      hits: 1 
                      url: "Sites/NetBeans/PHP-Cookie/second.php"
          }

          And so this cookie would look like while reading out with PHP.


          // OUTPUT CODE
          // In PHP
          object(stdClass)#1 (2) {
            ["totalvisits"]=>
            int(2)
            ["sites"]=>
            object(stdClass)#3 (2) {
              ["second"]=>
              object(stdClass)#2 (2) {
                ["url"] => string(36) "Sites/NetBeans/PHP-Cookie/second.php"
                ["hits"] => int(1)
              }
              ["index"]=>
              object(stdClass)#4 (2) {
                ["url"] => string(35) "Sites/NetBeans/PHP-Cookie/index.php"
                ["hits"] => int(1)
              }
            }
          }


          Of course we can also update the content of our cookies and in JavaScript also very well. We can fill our object arbitrarily and hold everything, but the size is limited. Perform the update function on a reload or with an event listener on one click. Expand the feature so you can gather the information you need, this is just one example.


          // JS CODE
             0  /**  1   * Update the cookie  2   *  3   * @param {string} name  4   */  5  function updateMyCookie(name) {  6    7      let date = new Date(),  8              visitorsOBJ = getMyCookie(name),  9              located = location.pathname.substr(1), // Request uri  10              totalcount = (visitorsOBJ.totalvisits + 1),  11              idx = setMyIndex(); // In loc, ours is the cleaned url basename, e.g. index.php becomes index and second.php becomes second, but first-slide.php also becomes firstslide  12    13      // If this object exists, we will update it, otherwise we will rebuild it and set our data  14      if (typeof visitorsOBJ.sites[idx] === 'object') {  15          visitorsOBJ.sites[idx].url = located;  16          visitorsOBJ.sites[idx].hits = visitorsOBJ.sites[idx].hits + 1;  17      } else {  18          visitorsOBJ.sites[idx] = {}; // Neues Objekt erstellen  19          visitorsOBJ.sites[idx].url = located;  20          visitorsOBJ.sites[idx].hits = 1;  21      }  22    23      // We set our time and override the current one  24      date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));  25    26      let args = {  27          name: name + "=" + JSON.stringify({  28              totalvisits: totalcount,  29              sites: visitorsOBJ.sites  30          }) + ';',  31          expires: "expires=" + date.toUTCString() + ';', // Now we put it in the right format  32          path: 'path=/;',  33          domain: 'domain=localhost;',  34          secure: 'secure=false;'  35      };  36    37      setMyCookie(args);  38  }  39    40  /**  41   * Help function  42   *   43   * @returns {string}  44   */  45  function setMyIndex() {  46      // Request uri  47      var loc = location.pathname.substr(1);  48      // Replace signs  49      loc = loc.replace("-", ");  50      loc = loc.replace(".php", ");  51      loc = loc.replace(/\/$/, ");  52      // Basename  53      loc = loc.split('/').reverse()[0];  54      return loc;  55  } 


            At some point, we may also want to remove our cookie or just a specific cookie. That's why we need one last feature that removes our cookie. Note here, if you have created your cookie with a path, you also need this when removing the cookie. We remove our cookie by simply putting the time into the past.


            // JS CODE
               0  /**  1   * Delete the cookie  2   *   3   * @param {string} name  4   */  5  function deleteMyCookie(name) {  6      document.cookie = name + '=; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Path=/; domain=localhost;';  7  } 


              Tip

              Look at this article too  PHP - Set and use cookies on, here was with PHP the cookie so that you can read this with the code above and vice versa exactly. So not only read the same cookie but also adjust the content exactly.



              Everything as a class

              And here is the complete code in class style, so that you can outsource and use what you should do. Even in a separate file so that you can open without the file recognizes which class it is. In order to keep the class clear not only as a file but also as a content, it should not be longer than 200 lines, that is the class itself. If it should go beyond that you can decide depending on the function if another class still comes into question and then outsource this as here, for example setMyIndex in MyHttp (here I would only get location path name and call the function get loc or something). The content also because they are replace functions that you could also outsource and with array replace provided as the class MyRegEx. So you could do a lot more :)


              // JS CODE
                 0  /**  1   * Description of Cookie  2   *  3   * @author      prod3v3loper  4   * @copyright   (c) 2023, prod3v3loper  5   * @package     MelAbu  6   * @version     0.6 alpha  7   * @since       0.6 alpha  8   * @link        https://www.tnado.com/  9   */  10  var MyCookie = {  11      /**  12       * Set the cookie  13       *   14       * @param {array} args  15       */  16      setMyCookie: function (args) {  17          if (MyCookie.enabledMyCookie() && args.name && args.expires && args.path && args.domain) {  18              document.cookie = args.name + args.expires + args.path + args.domain;  19          }  20      },  21      /**  22       * Check if the cookie exists  23       *   24       * @param {string} name  25       *  26       * @returns {bool}  27       */  28      hasMyCookie: function (name) {  29          if (name) {  30              return document.cookie.search(name) !== -1 ? true : false;  31          }  32      },  33      /**  34       * Check if cookies enabled  35       *  36       * @returns {bool}  37       */  38      enabledMyCookie: function () {  39          return navigator.cookieEnabled;  40      },  41      /**  42       * Get the cookie  43       *   44       * @param {string} name  45       *  46       * @returns {string}  47       */  48      getMyCookie: function (name) {  49          if (name) {  50              return JSON.parse(decodeURIComponent(document.cookie).replace(name + "=", ''));  51          }  52      },  53      /**  54       * Update the cookie  55       *   56       * @param {string} name  57       */  58      updateMyCookie: function (name) {  59    60          if (!name) { return };  61    62          let date = new Date(),  63                  visitorsOBJ = MyCookie.getMyCookie(name),  64                  located = location.pathname.substr(1),  65                  totalcount = (visitorsOBJ.totalvisits + 1),  66                  idx = MyCookie.setMyIndex();  67    68          // Update cookie values  69          if (typeof visitorsOBJ.sites[idx] === 'object') {  70              visitorsOBJ.sites[idx].url = located;  71              visitorsOBJ.sites[idx].hits = visitorsOBJ.sites[loc].hits + 1;  72          } else {  73              visitorsOBJ.sites[idx] = {};  74              visitorsOBJ.sites[idx].url = located;  75              visitorsOBJ.sites[idx].hits = 1;  76          }  77    78          // Set our time and overwrite the dateTime  79          date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));  80    81          let args = {  82              name: name + "=" + JSON.stringify({  83                  totalvisits: totalcount,  84                  sites: visitorsOBJ.sites  85              }) + ';',  86              expires: "expires=" + date.toUTCString() + ';',  87              path: 'path=/;',  88              domain: 'domain=localhost;',  89          };  90    91          MyCookie.setMyCookie(args);  92      },  93      /**  94       * Delete the cookie  95       *   96       * @param {string} name  97       */  98      deleteMyCookie: function (name) {  99          if (name) {  100              document.cookie = name + '=; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Path=/; domain=localhost;';  101          }  102      },  103      /**  104       * Set the index for cookie  105       *   106       * @returns {string}  107       */  108      setMyIndex: function () {  109          var loc = location.pathname.substr(1);  110          loc = loc.replace("-", ");  111          loc = loc.replace(".php", ");  112          loc = loc.replace(/\/$/, ");  113          loc = loc.split('/').reverse()[0];  114          return loc;  115      }  116  };  117    118  // Delete the cookies  119  // MyCookie.deleteMyCookie("Visitor");  120    121  if (MyCookie.hasMyCookie('Visitor')) {  122      MyCookie.updateMyCookie('Visitor');  123  } else {  124      var d = new Date(), args = {};  125      d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));  126      args = {  127          name: "Visitor=" + JSON.stringify({  128              totalvisits: 0,  129              sites: {}  130          }) + ';',  131          expires: "expires=" + d.toUTCString() + ';',  132          path: 'path=/;',  133          domain: 'domain=localhost;',  134          secure: 'secure=false;'  135      };  136      MyCookie.setMyCookie(args);  137  } 

                So you can apply it but not the user but the programmer in which you understand what you do and what the functions in detail.


                // HTML CODE
                   0  <!DOCTYPE html>  1  <html>  2      <head>  3          <meta charset="UTF-8">  4          <title>Cookies</title>  5          <link href="css/style.css" rel="stylesheet">  6          <!-- HERE IS OUR SCRIPT INTEGRATED -->  7          <script type="text/javascript" src="js/script.js"></script>  8      </head>  9      <body>  10          <div class="wrap">  11              <ul>  12                  <li><a href="index.php">Home</a></li>  13                  <li><a href="second.php">Second</a></li>  14              </ul>  15          </div>  16      </body>  17  </html> 

                  Then you can expand everything to your needs, such as to cut all file extensions;)

                  Advertising

                  Your Comment

                  * This fields are required, email don't publish
                  ?

                  This field is optional
                  Fill this field link your name to your website.

                  Data entered in this contact form will be stored in our system to ensure the output of the comment. Your e-mail address will be saved to determine the number of comments and for registration in the future

                  I have read the Privacy policy and Terms. I Confirm the submission of the form and the submission of my data.
                  tnado © 2024 | All Rights Reserved
                  Made with by prod3v3loper