What are JavaScript Cookies

A Javascript cookie is a little string text file that keeps information on your computer. They often save information like website preferences, inviting the user to enhance the web page the next time they return.

what-is-javascript-cookies

Cookies may be generated, retrieved, and updated directly using JavaScript, and the procedure is straightforward. This lesson will teach you about HTTP cookies and how you can use JavaScript to handle them efficiently.

All cookie data is instantly transmitted to the application server whenever a page is requested from the browser server. Since malicious individuals may get access to this data, cookies shouldn't be used to save sensitive data such as your credit card details or passwords.

Types of Cookies

There are three (3) kinds of Cookies and they are listed below with short explanations of what they mean and are useful for.

  1. First-party cookies are those produced by your website and can only be read by your website.
  2. Third-party cookies are created by third-party advertisements on your website. These cookies can only ever be read on websites that use the same advertising code to show the same ad.
  3. Session cookies are cookies that are stored on your browser. Whenever the browser gets closed, they are erased.

Structures of a Cookie

The cookie attribute of the Document object is used to create cookies. A cookie takes the following form:

name=value; expires=expirationDateGMT; path=URLpath; domain=siteDomain

1. Cookie Name

The first portion of the cookie specifies the cookie's name as well as the value supplied to it. The name, as well as value settings, could both be whatever you want. You might wish to save a user's currency selection, such as currency=NGNaira. This is the sole necessary section of the cookie. If the following settings are not necessary, they can be removed from the cookies.

2. Cookie Expiration

The expires= part, which is optional, indicates when the cookie should expire. For this reason, the JavaScript Date Object may be used to get and modify dates.

To configure a cookie to expire in Five (5) months, for example:

var expirationDate = new Date;
expirationDate.setMonth(expirationDate.getMonth()+5)

3. Cookie Path

The path= parameter allows a URL (Link) to be saved in the cookie. Cookies are only available by default to the web pages which are in the same directory as the web page that produced the cookie. For instance, if the cookie was established when the user accessed http://www.hubtolearn.com/home/index.html, it will be visible to all other sites in the /home directory but will not be visible to pages in the /navigate directory. This restriction is eliminated by setting path=/navigate.

4. Cookie domain

Cookies, like path settings, are only visible to web pages hosted on the server domain from where the cookie originated. A cookie produced by a web page housed on www.hubtolearn.com, for instance, is not available by default to a web page hosted on www.faqontech.com. With a domain=faqontech.com option, you can allow cookie access from websites on faqontech.com.

What Can Cookies Not Do?

  1. Cookies can only identify the device being used, not the user.
  2. Internet browsers these days are supposed to be able to save at least three-hundred four-kilobyte (4 kb) cookies per domain or server.
  3. You can save up to twenty cookies for each path and domain.
  4. Cookies can only be accessed by the visitor's device that produced the cookie.
  5. A website can only read and set its own cookies (for instance, Yahoo cannot read Internet Explorer's cookies).

Why are Cookies Useful?

Cookies are used for the following purposes:

  1. Cookies enable you to handle any information which the server should remember throughout a session. Login information, shopping carts, and the like.
  2. Personalization - Cookies enable you to save user preferences, layouts, and settings that are unique to each user.
  3. Tracking cookies aid in the recording and analysis of user activities in advertising.

Creating JavaScript Cookies

We can now check out the process of creating JavaScript Cookies, given that you understand what they are as well as understanding how they are built. Cookies, as previously described in this article, are generated by utilizing the cookie attribute of the Js Document object.

In the example below, we will ask the user for their name and then save it to a cookie on their device.

<html>
<head>
<title>Example Creating JavaScript Cookie</title>
<script language=javascript type="text/javascript">


function writeCookie( )
{
        var name = document.orderForm.nameField.value; // Retrieve the name of the user
        document.cookie = "yourName=" + name; // Create a cookie
}

</script>
</head>

<body>
<form action="" name="orderForm">
Input your name: <input type="TEXT" name="nameField"/>
<input type="BUTTON" value="Write Cookie" onClick="writeCookie()" />
</form>

</body>
</html>

Reading a Cookie

Once a cookie has been written, it may be read back. We will now modify our example by including a "Read Cookie" button that will read the cookie value and publish it to the browser document. Because the cookie's value=pair is really a Js String object, we can employ the String split() function to separate the name=value pair at the = to extract only the value (Check out this article -  JavaScript String Object). As an example:

var yourName = document.cookie.split("=")[1];

We can now change our previous example to read our cookie & show the value to which it has been assigned:

<html>
<head>
<title>Example Creating JavaScript Cookie</title>
<script language=javascript type="text/javascript">


function writeCookie( )
{
        var name = document.orderForm.nameField.value;
        document.cookie = "yourName=" + name;
}

function readCookie( )
{
        if (document.cookie != "") //check that the cookie is in existence
        {
                var yourName = document.cookie.split("=")[1]; //Get the value from the name=value pair
                document.write ("Hello, " + yourName);
        }
}
</script>
</head>

<body>
<form action="" name="orderForm">
Enter your name: <input type="TEXT" name="nameField"/>
<input type="BUTTON" value="Write Cookie" onClick="writeCookie()" />
<input type="BUTTON" value="Read Cookie" onClick="readCookie()" />
</form>

</body>
</html>

Updating Cookies

Cookies can be modified by changing the cookie characteristics, i.e, Setting fresh values.

Deleting Cookies

Simply rename a cookie with the same name, supply an empty value, or you can set its max-age property to 0 to delete it.

If you supplied the cookie's domain and path, you must include them when removing it.

Simply modify the value (expiration date) to a past date to erase a cookie using the expires attribute.

            function eraseCookie(cname) {
                 createCookie(cname, "", -1);
            }