Cookies in JavaScript

Sourav.Kayal
Posted by in JavaScript category on for Beginner level | Points: 250 | Views : 4074 red flag

In this article we will learn to use cookies in JavaScript

Cookies in JavaScript

In this article we will learn to use cookie in JavaScript. We know that HTTP is stateless protocol means each and every request to web server is new. It does not remember previous history of request. So, to maintain persistence between requests we can use various techniques. They are called state management techniques.

Cookie is one of the client side state management techniques. It’s nothing but a simple text file which store in user’s browser. The size of file should be very small (approximately 5 KB) and the limitation of cookie per domain is limited. As it is plain text file and easy to read, it’s recommended not to store sensitive information within cookie.

Types of cookies

Cookies are two types in nature.

Persistence cookies:- This type of cookies remain active event after close of browser window. There is certain time limitation for them, it might be few days or few years.

Non-persistence cookies:- This type of cookies delete automatically after the browser close.

 

Create cookie in JavaScript

In this example we will create one simple cookie. Have a look on below example.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
    <script>
        document.cookie = "name=" + 'Sourav Kayal';
        console.log(document.cookie.split(';'));
    </script>
</body>
</html>


Show all cookies

We can show all cookies of certain domain by calling cookie property of document object. It will show all the cookies of particular domain. It’s not possible to access cookies of one domain from another domain.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
    <script>
        console.log("Name of cookies:- " + document.cookie);
    </script>
</body>
</html>


Show all cookies with key value pair

This is another way to show all the cookies. In this example we will print all the cookies with key value pair. At first we will extract all cookies from document object and after that we will go throw all of them using for loop.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
    <script>
 
        //Get all cookies in variable
        var cookies = document.cookie;
       
        // Split all the cookies by ; separator
        ArrayCook = cookies.split(';');
 
        // Now take key value pair out of this array using for loop
        for (var i = 0; i < ArrayCook.length; i++) {
            name = cookiearray[i].split('=')[0];
            value = cookiearray[i].split('=')[1];
            console.log("Key is : " + name + " and Value is : " + value);
        }
 
    </script>
</body>
</html>

 

Set persistent cookie

We can create persistent cookie by attaching expires property of cookie. In this example we are creating one cookie which will stay in computer for 1 month. Have a look on below code.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
    <script>
 
        var today = new Date();
        today.setMonth(today.getMonth() + 1);
        cookievalue = 'Sourav Kayal';
        document.cookie = "name=" + cookievalue;
        document.cookie = "expires=" + today.toUTCString() + ";"
        console.log("Cookie set : " + "name=" + cookievalue);
 
    </script>
</body>
</html>

 

Delete cookie

It’s possible to delete persistent cookie programmatically for that we have to set negative date to particular cookie. Here is sample example to delete any cookie from computer.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
    <script>
 
        var today = new Date();
        today.setMonth(today.getMonth() - 1);
        cookievalue = 'Sourav Kayal';
        document.cookie = "name=" + cookievalue;
        document.cookie = "expires=" + today.toUTCString() + ";"
        console.log("Deleted Cookie : " + "name=" + cookievalue);
 
    </script>
</body>
</html>


Conclusion:-

In this article we have discusses about cookie in JavaScript. As we have discusses it’s recommended not to store sensitive data into it. Cookies are limited in size and number.

 

 

Page copy protected against web site content infringement by Copyscape

About the Author

Sourav.Kayal
Full Name: Sourav Kayal
Member Level: Silver
Member Status: Member,MVP
Member Since: 6/20/2013 2:09:01 AM
Country: India
Read my blog here http://ctrlcvprogrammer.blogspot.in/
http://www.dotnetfunda.com
I am .NET developer working for HelixDNA Technologies,Bangalore in healthcare domain. Like to learn new technology and programming language. Currently working in ASP.NET ,C# and other microsoft technologies.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)