How to access cookies using document object in JavaScript?


With JavaScript, you can easily access/ read cookies with the “document.cookie” property. Reading a cookie is just as simple as writing one because of the value of the document.cookie object is the cookie.

The document.cookie string will keep a list of name=value pairs separated by semicolons, where the name is the name of a cookie and value is its string value.

In this article, we will learn how to access cookies using document object in JavaScript.

Syntax

document.cookie

Return value − All the cookies are saved in the browser in a single string.

The document.cookie string will keep a list of name=value pairs separated by semicolons, where the name is the name of a cookie and value is its string value.

Steps

To extract a specific cookie using its name we use the following steps.

  • Get all the cookie string using the document.cookie property.

  • Split the string at every semicolon (“;”) using the String.split( ) method and store the returned array in a variable.

  • Create an empty Map( ) to store the key-value pairs.

  • Loop through the array and at every iteration split that element at “=” and set its 0th index as Map’s key and first index as Map’s value using the Map.set ( key, value ) method.

  • Now you have every cookie as its name=value format in the Map( )

  • Retrieve the desired cookie by its name from the Map( ).

Example

You can try to run the following code to learn how to access cookies using document object in JavaScript

<html>
   <head>
      <script>
         function ReadCookie() {
            var allcookies = document.cookie;
            document.write ("All Cookies : " + allcookies );
            
            // Get all the cookies pairs in an array
            cookiearray = allcookies.split(';');
            
            // Now take key value pair out of this array
            for(var i=0; i<cookiearray.length; i++) {
               name = cookiearray[i].split('=')[0];
               value = cookiearray[i].split('=')[1];
               document.write ("Key is : " + name + " and Value is : " + value);
            }
         }
      </script>
   </head>
      <body>
         <form name="myform" action="">
            <p> Click the following button to access the cookie:</p>
            <input type="button" value="Get Cookie" onclick="ReadCookie()"/>
         </form>
      </body>
</html>

Example

In this example first, we are setting some cookies using the document.cookie method and then we retrieve the cookie by its name using the approach described above.

<!DOCTYPE html>
<html>
   <head>
      <title> How to access cookies using document object in JavaScript </title>
   </head>
   <body>
      <h2> Accessing cookies using document object in JavaScript </h2>
   </body>
   <script>

      // Set some cookie to the browser
      document.cookie = "firstname=Saurabh"
      document.cookie = "lastname=Jaiswal"
      document.cookie = "age=20"

      // Print the cookie string
      document.write( document.cookie + "  ")

      // firstname=Saurabh; lastname=Jaiswal; age=20
      // There can be another cookie also printed
      // if they are saved previously in your browser

      // Get the cookie and store in a variable
      let myCookies = document.cookie
      myCookies = "firstname=Saurabh;lastname=Jaiswal;age=20"

      // Split the cookie string at every semicolon
      myCookies = myCookies.split(";")

      // ['firstname=Saurabh', ' lastname=Jaiswal', ' age=20']
      // Create a map to store the cookies in key value Pair
      let cookies = new Map();

      // Loop through the myCookies array
      for( let cookie of myCookies ){

         // Split the elements at "="
         cookie = cookie.split( "=" )

         // Set the first element as key and second element as value
         cookies.set( cookie[0], cookie[1] )
      }
      // Retrive the cookies by its name
      document.write( cookies.get( "firstname" ) + "  ");
      document.write( cookies.get( "lastname" ) + "  );
      document.write( cookies.get( "age" ) + "  ");
   </script>
</html>

In summary, JavaScript allows you to access and read cookies using the document.cookie property. This property returns a string containing all the cookies saved in the browser, with each cookie represented as a name=value pair separated by a semicolon.

To extract a specific cookie using its name, you can split the cookie string at every semicolon, create a Map object to store the key-value pairs, and loop through the array of cookie pairs, setting the first element as the key and the second element as the value in the Map. You can then retrieve the desired cookie by its name from the Map. This technique can be useful for storing and retrieving information in a user's browser, such as user preferences or login credentials.

Updated on: 06-Jan-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements