A cookie is a Temporary Web Storage File, which stores the keywords searched by the user on the Internet or filled information up to the time period set by the server. It is known by many names, such as Web Cookie, Browser Cookie, and HTTP Cookie.

In this article, we’ll discuss JavaScript get cookie by name and Set cookie and get a cookie with JavaScript.
I’m working on website design in which I’m trying to set a cookie depending on which I will add reference of Javascript file in my HTML Page.

I have an HTML page with a list of HTML control options, and different Javascript files as values. So for completing this task I have written javascript code for Set, Delete, and Read cookie value by name in JavaScript.Let’s have a look

A cookie is mainly of 2 Type,

Session Cookie: Cookie that automatically deletes as soon as the browser is closed is called Session Cookie. Its use is mostly for government websites or if you build a highly secure website.

Permanent Cookie: cookie that presents in the browser even after closing Browser, the information you have searched or filled on the Internet, is stored for 1 Day, 1 Month, or 1 year. All such cookie is called Permanent Cookie. This type of cookie is used for Travel or Online Booking Website.

How do cookies work?

When any website is created, cookies are made by Web Developers. As soon as you open such a website. It lets you drop your cookies file on your Computer Browser.

After cookies are set on your browser, it works like Cache Memory and whatever you search on the Internet. Cookies keep storing that information and send it to their website server.

In this Part I will explain you Following Points:-

  • How to Deal with Cookies in JavaScript
  • Set cookie and get cookie with JavaScript
  • How to set cookie’s expire date with JavaScript?
  • Setting cookie to expire after x day

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>

 

Create Cookie:-

Below is a simple code for creating Cookies in the Browser, you can say that cookies are plain text data with a record of 5 i.e
  • Expires − The date when you the cookie will expire. If you set this value blank, then the cookie will expire when the user closes the browser. These cookies also are known as Session Cookie or temporary cookies.
  • Domain −Url of your Web Application.
  • Path − The path web page that sets the cookie. you can set value blank if you want to read the cookie from any page.
  • Secure − if you set this field “secure”, then the cookie only be retrieved with a secure server like only with https.
  • Name and Value − Cookies are store in the form of key-value pairs. using this property 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 any browser, some information gets from our phone or our computer in the form of a file, as which keyword you have used and which website you have opened, then all such information is saved in a file and kept in our mobile computer data. given so that it can be used later.

Like we told you that whenever we search on the browser, then their small files are saved in our computer or our phone. With this, a message is sent to the website server whenever we open a site or do some search, all its data is saved in a file. When you go to the site, you are shown many such things that you have searched before or that you are interested in. This happens because a file of cookies is saved in our mobile or our computer, and then all the advertisements are shown on the Internet accordingly.

Cookies can be used easily and can also be implemented.
It takes very little data to save the file on the server, which is a big advantage of it.
When our browser is closed for some reason, then using this we can open our opened tab again. It help a lot to save time and save data.

Cookies depend on all browsers, such as if you use Chrome browser, then you will not be able to use their cookies in other browsers like Internet Explorer, Firefox. Also depend on the domain because the data taken from one domain will not be able to tell about the other domain.Cookies file is about 4KB, which can be of different size in different browsers.

The post [Solved]-Set,Delete and Read cookie value by name in JavaScript appeared first on Software Development | Programming Tutorials.



Read More Articles