JavaScript Cookies

JavaScript Cookies allows you to store data on web page.

What are JavaScript cookies?

Cookies are data stored in small files on a user’s computer.

When a request is completed by web server, the connection with the server is terminated and there is no information of user with the server.

Cookies are use to remember the user data.

When a user visits a web page, user information for example say user’s total visit on web page is stored in a cookie. When user visits the web page next time, it shows user’s total visits from cookie data.

Cookies are store as a name value pair.

totalvisits = 3;

When a browser requests a webpage from a server, all cookies relate to that domain is sent with the request. Hence server can get data of cookies.

Create cookies

JavaScript can create, read, modify or delete cookies. JavaScript uses document.cookie property for this.

Using JavaScript cookies can be create as below.

document.cookie = "totalvisits=3";

You can add cookie expire time when creating a new cookie. Expire time must be in UTC format. If expire time is not provided, it will delete when browser is close.

document.cookie = "totalvisits=3; expires=Sun, 25 Dec 2016 12:00:00 UTC";

There is a path parameter using it, you can define the cookie belongs to which page. If path parameter is not set, cookie is set for current page.

document.cookie = "totalvisits=3; expires=Sun, 25 Dec 2016 12:00:00 UTC; path = /";

Read Cookie

You can read cookies using JavaScript as below:

var c=document.cookie;

Above statement returns all the cookie belongs to current page.

Modify Cookie

You can modify cookies same way you can create a cookie. If cookie is create with same name as existing cookie it will replace old cookie.

document.cookie = "totalvisits=4; expires=Sun, 25 Dec 2016 12:00:00 UTC; path = /";

Delete a Cookie

It is easy to delete cookie. To delete cookie just set cookie expire time in past.

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

Cookie String

Cookie value looks like normal string.

If you create a new cookie, old cookies are not overwritten, but new cookie is append to old cookie string.

There is no direct way to access one cookie value, you should create custom function to retrieve one cookie value.

Cookie Example

First time user visits page, we will store its visit count to cookie. When user visits next time we will check if user has visited a page before, if so than retrieve value of user visit count, increment it and store it again in cookie.

We will create below functions.

  • Set: A function to set a cookie value
  • Get: A function to get a cookie value
  • Check: A function to check a cookie value

A Function to Set a Cookie

First we will create a function to set a new cookie.

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
} 

In above function, cname is cookie name, cvalue is cookie value and exdays is cookie expiry in days.

A Function to Get a Cookie

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
        }
    }
    return "";
} 

Above function retrieve cookie value based on given cookie name. It splits cookie string with semicolon(;) and retrieve all cookies in an array. Than it compares cookie name within array. Once match is found it retrieve its value and return it.

A Function to Check a Cookie

function checkCookie() {
    var visits=getCookie("totalvisit");
    if (visits!="") {
        setCookie("totalvisit", (parseInt(visits)+ 1), 365);
        alert("Total visits " + visits);
    } else {
        setCookie("totalvisit", 1, 365);
    }
} 

Complete Example

<!DOCTYPE html>
<html>
<body>

Display the pixel depth of the screen:
<p id="screencolor"></p>

<script>
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
} 

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
        }
    }
    return "";
} 

function checkCookie() {
    var visits=getCookie("totalvisit");
    if (visits!="") {
        setCookie("totalvisit", (parseInt(visits) + 1), 365);
        alert("Total visits " + visits);
    } else {
        setCookie("totalvisit", 1, 365);
		alert("You visited for the first time.");
    }
} 

checkCookie();
</script>

</body>
</html>

Download the code Run the code

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .