Set and use JavaScript cookies

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   * @param {array} args  3   */  4   function setMyCookie(args) {  5        document.cookie = args.name + args.expires + args.path + args.domain;  6   } 

    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  var d = new Date(), args = {};  2  // Set expiry time, here 365 days  3  d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));  4  // Dann unser objekt für 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   * @param {string} name  3   * @returns {string}  4   */  5  function hasMyCookie(name) {  6      return document.cookie.search(name) !== -1 ? true : false;  7  } 

        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   * @param {string} name  3   * @returns {string}  4   */  5  function getMyCookie(name) {  6      return JSON.parse(decodeURIComponent(document.cookie).replace(name + "=", ''));  7  } 

          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   * @param {string} name  3   * @returns {string}  4   */  5  function updateMyCookie(name) {  6    7      var 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      var 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 {basename}  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   * @returns {string}  5   */  6  function deleteMyCookie(name) {  7      document.cookie = name + '=; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Path=/; domain=localhost;';  8  } 


              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      Samet Tarim  4   * @copyright   (c) 2018, Samet Tarim  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 {type} args  15       * @returns {undefined}  16       */  17      setMyCookie: function (args) {  18          if (MyCookie.enabledMyCookie() && args.name && args.expires && args.path && args.domain) {  19              document.cookie = args.name + args.expires + args.path + args.domain;  20          }  21      },  22      /**  23       * Check if the cookie exists  24       *   25       * @param {string} name  26       * @returns {string}  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       * @returns {navigator.cookieEnabled|Boolean}  36       */  37      enabledMyCookie: function () {  38          return navigator.cookieEnabled;  39      },  40      /**  41       * Get the cookie  42       *   43       * @param {string} name  44       * @returns {string}  45       */  46      getMyCookie: function (name) {  47          if (name) {  48              return JSON.parse(decodeURIComponent(document.cookie).replace(name + "=", ''));  49          }  50      },  51      /**  52       * Update the cookie  53       *   54       * @param {string} name  55       * @returns {string}  56       */  57      updateMyCookie: function (name) {  58    59          if (!name) { return };  60    61          var date = new Date(),  62                  visitorsOBJ = MyCookie.getMyCookie(name),  63                  located = location.pathname.substr(1),  64                  totalcount = (visitorsOBJ.totalvisits + 1),  65                  idx = MyCookie.setMyIndex();  66    67          // Update cookie values  68          if (typeof visitorsOBJ.sites[idx] === 'object') {  69              visitorsOBJ.sites[idx].url = located;  70              visitorsOBJ.sites[idx].hits = visitorsOBJ.sites[loc].hits + 1;  71          } else {  72              visitorsOBJ.sites[idx] = {};  73              visitorsOBJ.sites[idx].url = located;  74              visitorsOBJ.sites[idx].hits = 1;  75          }  76    77          // Set our time and overwrite the dateTime  78          date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));  79    80          var args = {  81              name: name + "=" + JSON.stringify({  82                  totalvisits: totalcount,  83                  sites: visitorsOBJ.sites  84              }) + ';',  85              expires: "expires=" + date.toUTCString() + ';',  86              path: 'path=/;',  87              domain: 'domain=localhost;',  88          };  89    90          MyCookie.setMyCookie(args);  91      },  92      /**  93       * Update the cookie  94       *   95       * @param {string} name  96       * @returns {string}  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;)

                  Your Comment

                  * This fields are required, email don't publish
                  You can use this tags: <p>, <em>, <strong>, <u>, <s>, <pre>, <blockquote>
                  ?

                  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 SEO & AMP CMS © 2019 | All Rights Reserved
                  Created with tnado SEO CMS