A cookie is a temporary web storage file that stores keywords searched by the user on the internet or filled information for a period set by the server. It is known by various names such as Web Cookie, Browser Cookie, and HTTP Cookie.

In this article, we'll discuss how to get a cookie by name and set a cookie using JavaScript. I'm currently working on website design where I'm attempting to set a cookie, based on which I will add a reference to a JavaScript file in my HTML page.

I have an HTML page containing a list of HTML control options, with different JavaScript files as values. To accomplish this task, I've written JavaScript code to set, delete, and read cookie values by name. Let's take a look.

A cookie is mainly of 2 Type,

Session Cookie: This type of cookie automatically deletes as soon as the browser is closed. It's commonly used for government websites or when building highly secure websites.

Permanent Cookie: A permanent cookie remains in the browser even after it's closed. It stores information such as searches or form entries for a specified duration, typically 1 day, 1 month, or 1 year. These cookies are often used by travel or online booking websites.

How do cookies work?

When a website is created, cookies are generated by web developers. Once you visit such a website, it places cookies on your computer browser.

Once cookies are set in your browser, they function similarly to cache memory. They store information about your internet activities and send this data to the website's server.

In this part, I will explain the following points:

  • How to Handle Cookies in JavaScript
  • Setting and Retrieving Cookies with JavaScript
  • How to Set the Expiry Date of a Cookie with JavaScript
  • Setting a Cookie to Expire After X Days

Html Code

<!DOCTYPE html>
<html>
<head>
    <title>DotNetPeTips</title>
    <meta charset="utf-8" />
</head>
<body>
    <fieldset>
        <legend>Create Cookie</legend>
        <button type="button" onclick="CreateCookie('testcookie',10,'testing cookie message')">Create Cookie</button>
        <button type="button" onclick="getCookie('testcookie')">Read Cookie</button>
        <button type="button" onclick="DeleteCookie('testcookie')">Delete Cookie</button>
    </fieldset>
    <script type="text/javascript">
        function SetCookie(cookie_name, days,value) {
            debugger;
            var today = new Date();
            var expiresdate = new Date(today.setTime(today.getTime() + days * 86400000));
            document.cookie = cookie_name + "=" + value + "; expires=" +
            expiresdate.toGMTString();
            alert("cookie set successfully!");
        }

        function getCookie(cookie_name) {
            if (document.cookie.length > 0) {
                cookie_start = document.cookie.indexOf(cookie_name);
                if (cookie_start) {
                    cookie_start = cookie_start + cookie_name.length + 1;
                    cookie_end = document.cookie.indexOf(";", cookie_start);
                    if (cookie_end == -1) {
                        cookie_end = document.cookie.length;
                    }
                    alert(unescape(document.cookie.substring(cookie_start, cookie_end)));
                    return unescape(document.cookie.substring(cookie_start, cookie_end));
                }
            }
            return "";
        }

        function DeleteCookie(cookie_name) {
            debugger
            SetCookie(cookie_name, '', -2)
        }
    </script>
</body>
</html>

 

  • SetCookie(cookie_name, days, value): This function sets a cookie with the provided name, value, and expiry date. It takes three parameters: cookie_name (the name of the cookie), days (the number of days until the cookie expires), and value (the value to be stored in the cookie).
  • Inside the function:It calculates the expiry date by adding the specified number of days to the current date.It then sets the cookie using document.cookie, specifying the name, value, and expiry date using expires.Finally, it displays an alert indicating that the cookie has been set successfully.
  • getCookie(cookie_name): This function retrieves the value of a cookie by its name. It takes one
  • parameter: cookie_name (the name of the cookie). 
  • Inside the function:It checks if there are any cookies stored in the document.If cookies are found, it searches for the specified cookie_name within the stored cookies.If the cookie is found, it retrieves its value and returns it after unescaping any encoded characters.If the cookie is not found, it returns an empty string.
  • DeleteCookie(cookie_name): This function deletes a cookie by setting its expiry date to a past date. It takes one parameter: cookie_name (the name of the cookie). 
  • Inside the function:It calls the SetCookie function with an empty string for the value parameter and a negative value for days, effectively setting the cookie's expiry date to the past, hence deleting it.

These functions provide basic cookie manipulation capabilities for managing cookies in a web browser using JavaScript.

Create Cookie:-

Below is a simple code for creating cookies in the browser. Cookies are essentially plain text data with five main attributes:

1. Expires: The date when the cookie will expire. If you leave this value blank, the cookie will expire when the user closes the browser. These cookies are also known as Session Cookies or temporary cookies.

2. Domain: The URL of your web application.

3. Path: The path of the webpage that sets the cookie. You can leave this value blank if you want to read the cookie from any page.

4. Secure: If you set this field to "secure", then the cookie can only be retrieved with a secure server, such as only with HTTPS.

5. Name and Value: Cookies are stored in the form of key-value pairs. Using this property, you can define the name of the cookie, which will help you when reading the cookie value.
 function SetCookie(cookie_name, days,value) {
            debugger;
            var today = new Date();
            var expiresdate = new Date(today.setTime(today.getTime() + days * 86400000));
            document.cookie = cookie_name + "=" + value + "; expires=" +
            expiresdate.toGMTString();
            alert("cookie set successfully!");
        }

 

Read Cookie:-

Reading a cookie value very simple,the value of the document.cookie object is the cookie.

 function getCookie(cookie_name) {
            if (document.cookie.length > 0) {
                cookie_start = document.cookie.indexOf(cookie_name);
                if (cookie_start) {
                    cookie_start = cookie_start + cookie_name.length + 1;
                    cookie_end = document.cookie.indexOf(";", cookie_start);
                    if (cookie_end == -1) {
                        cookie_end = document.cookie.length;
                    }
                    alert(unescape(document.cookie.substring(cookie_start, cookie_end)));
                    return unescape(document.cookie.substring(cookie_start, cookie_end));
                }
            }
            return "";
        }

Delete Cookie:-

If you want to delete a cookie then you just need to set the expiry date to a time in the past.

 function DeleteCookie(cookie_name) {
            debugger
            SetCookie(cookie_name, '', -2)
        }

 

Whenever you use a browser, certain information from your phone or computer is stored as a file. This information includes the keywords you've used and the websites you've visited. These details are saved in a file on our mobile devices or computers so they can be accessed later.

When we search using a browser, small files are stored on our devices. Additionally, whenever we visit a website or perform a search, data is saved in a file. This data is then used to personalize our browsing experience. For example, we might see advertisements related to our past searches or interests. This is possible because a file called cookies is saved on our devices, and advertisements are tailored based on its contents.

Cookies are easy to use and implement. They require minimal data storage on the server, which is a significant advantage. Furthermore, cookies allow us to reopen previously opened tabs if our browser is closed unexpectedly. This feature saves time and data.

Cookies are specific to individual browsers. For instance, cookies saved in the Chrome browser cannot be used in other browsers like Internet Explorer or Firefox. Additionally, cookies are domain-dependent, meaning data collected from one domain cannot be accessed by another domain. The size of a cookies file is typically around 4KB, although it may vary in different browsers.