JavaScript Cookies – How to Create, Read and Delete Cookies?

Last updated on Apr 17,2024 7.2K Views

JavaScript Cookies – How to Create, Read and Delete Cookies?

edureka.co

Cookies help you store user information in web pages. It is one of the most efficient methods of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics. In this JavaScript Cookies article, we will get into the depth of cookies in the following sequence:

What are Cookies?

Cookies are data stored in small text files in your system. When a web server sends a web page to a browser, the connection shuts down, and the server forgets everything about the user.

Cookies were invented to solve the problem of remembering the information about the user. For example:

It remembers the user’s information among all the web pages. It contains the information as a string and in the form of a name-value pair separated by semi-colons such as:

username = Daisy Green

Now let’s see how these cookies work.

Turn your passion for design into a career with our UI UX Design Certification Course.

How Does it Work?

The server sends some data to the visitor’s browser in the form of a cookie. Now, the browser may accept the cookie. If it does, it is stored as a plain text record on the visitor’s hard drive.

When the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once it is retrieved, your server knows or remembers what was stored before.

Cookies consist of 5 variable-length fields:

Now that you know what are cookies and how it works, let’s get into the depth of JavaScript cookies.

JavaScript Cookies

In JavaScript, you can manipulate cookies with the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page. So let’s have a look at examples and understand how cookies are used in JavaScript.

Create Cookies

JavaScript can create cookies with the document.cookie property. You can create the cookie in the following way:

document.cookie = "username=Daisy Green";

You can also add an expiry date for your cookie. By default, the cookie will be deleted when the browser is closed:

document.cookie = "username=Daisy Green; expires=Mon, 26 Aug 2019 12:00:00 UTC";

You can also tell the browser what path the cookie belongs to with the help of a parameter. By default, the cookie belongs to the current page.

document.cookie = "username=Daisy Green; expires=Mon, 26 Aug 2019 12:00:00 UTC"; path=/";

Read a Cookie

Reading a cookie is as simple as writing one because of the value of the document.cookie object is the cookie. You can use this string whenever you want to access the cookie. The document.cookie string keeps a list of name=value pairs separated by semicolons, where name represents the cookie name and value is its string value.

JavaScript Cookies can be read in the following way:

var x = document.cookie;

Example:


<html>
   <head>   
      <script type = "text/javascript">
         <!--
            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 Button to View Result:</p>
         <input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
      </form>      
   </body>
</html>

Output:

Change Cookies

JavaScript Cookies can be changed in the same way you create it:

document.cookie = "username=Mary Lian; expires=Fri, 18 Sep 2019 12:00:00 UTC; path=/";

Here, the old cookie will be overwritten.

Example:

<html>
   <head>   
      <script type = "text/javascript">
         <!--
            function WriteCookie() {
               var now = new Date();
               now.setMonth( now.getMonth() + 1 );
               cookievalue = escape(document.myform.customer.value) + ";"
               
               document.cookie = "name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>      
   </head>
   
   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>      
   </body>
</html>

Output:

Delete a Cookie

You might want to delete a cookie so that subsequent attempts to read the cookie returns nothing. To delete a cookie, you just need to set the expiry date to a time in the past.

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Example:

<html>
   <head>   
      <script type = "text/javascript">
         <!--
            function WriteCookie() {
               var now = new Date();
               now.setMonth( now.getMonth() - 1 );
               cookievalue = escape(document.myform.customer.value) + ";"
               
               document.cookie = "name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write("Setting Cookies : " + "name=" + cookievalue );
            }
          //-->
      </script>      
   </head>
   
   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>      
   </body>
</html>

With this, we have come to the end of JavaScript Cookies. I hope you understood how you can create, read, modify and delete cookies.

Now that you know about JavaScript Loops, check out the Web Development Certification Training by Edureka. Web Development Certification Training will help you learn how to create impressive websites using HTML5, CSS3, Twitter Bootstrap 3, jQuery and Google APIs and deploy it to Amazon Simple Storage Service(S3). 

Check out the Angular Certification Training Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Angular is a JavaScript framework that is used to create scalable, enterprise, and performance client-side web applications. With Angular framework adoption being high, performance management of the application is community-driven indirectly driving better job opportunities.

If you want to get trained in React and wish to develop interesting UI’s on your own, then check out the React JS Certification Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

Got a question for us? Please mention it in the comments section of “JavaScript Cookies” and we will get back to you.

Upcoming Batches For UI UX Design Certification Course
Course NameDateDetails
UI UX Design Certification Course

Class Starts on 15th June,2024

15th June

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES