How to Use Cookies in JavaScript



The HTTP protocol, which uses by Web Browser and Server to communicate, is a stateless protocol, means once the server send a response to a browser of the request, it doesn’t remember a thing about it. To solve this problem cookies were invented. There are other ways also to solve this but cookies are easy to use and very versatile. So in this article I will explain how to use Cookies in JavaScript.

A cookie is a piece of data like a small text file which is sent from a website and stored locally by the user’s browser. It is like several key-value pairs. Pairs are separated by semicolon and equal sign separate key and its value. It uses 5 variable-length fields as below:

Expires : The date when the cookie will expire. If it is blank, cookie will expire when user close the browser.
Domain : The domain name of the website.
Path : The path to the directory that set the cookie. If blank you can retrieve the cookie from any directory or page.
Secure : If this contains the word “secure” then the cookie may only be retrieved with a secure server. If this field is blank then no any restriction exists.
Name=Value : Cookies are set and retrieved in the form of key-value pairs.

Write Cookie: Simple way to create a cookie to assign a string value to the document.cookie object.

document.cookie = "key1=value1;key2=value2;expires=date";

Following is the script to set/write the cookie. You can use it like setCookie(‘name’,’value’); expires as number of days.

function setCookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	if ( expires ){
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

Read Cookie: Reading a cookie is also simple as writing, because you can use value of the document.cookie object whenever you want to access the cookie. It keeps a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value.

Following script with split() function is used to get the value of key. You just need to pass the key to the function and you will get the value of the cookie.

function readCookie(name){
	var nameEQ=name+"=";
	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,c.length);
			if(c.indexOf(nameEQ)==0)
				return c.substring(nameEQ.length,c.length)
		}
	return null
}

Delete Cookie : To delete a cookie just write the cookie with the expired/old date. Just like as below.

function deleteCookie( name, path, domain ) {
    if ( readCookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

LIVE DEMO

How to Use Cookies in JavaScript
How to Use Cookies in JavaScript