Cookies

Cookies are small text based files that are sent from a website and stored locally by the users browser. They are required because HTTP has no way to keep track of a user's activity (i.e. stateless).

 

They have a maximum size of 4KB, for all attributes (e.g. name, key/values pairs)

 

Cookies can be used for various purposes from storing the user's name to their last visit.

 

Cookies have a very specific format that must be adhered to, and cannot include white space, semi-colons or commas.

 

They consist of several name/value pairs that are separated by a semi-colon.

 

The key/value is separated with an equals sign.

 

An optional expiration can be included, after which time it's deleted. If there's no expiration date, the cookie is deleted at the end of the session, or when the browser is closed.

 

Date has to be in UTC/GMT format.

 

Domain and Path can be specified where the cookie can be read / written. Default path is '/' (meaning visible to all paths in the domain), and if no path is specified it will belong to the page that set the cookie

 

The specific order for setting a cookie should be:

  • Name-value pair containing the actual data
  • Expiry date after which it is no longer valid
  • Path within the domain
  • Domain of the server it should be sent to

name-value;expiration_date;path;domain;

 

 

To create, read and delete cookies the document.cookie method is used:

 

document.cookie = "lastVisit=Thurs, 02 Aug 2013 09:53:00 GMT; expires=Thurs, 09 Aug 2013 00:00:00 GMT;";

document.cookie = "userLevel=novice;"

 

Use the console with the following to see the result:

 

console.log(document.cookie);

 

 

To delete a cookie, simply set its date in the past.

 

This example has three functions to create, read and delete cookies. Two cookies are created and two buttons trigger the read and delete functions:

<html>
	<head>
		<title>JavaScript</title>
	</head>
	<body>
		<h1>Creating, reading and deleting cookies!</h1>
		<p id="info"></p>
		<script>
			function createCookie(name,value,days) {
				if (days) {
					var date = new Date();
					date.setTime(date.getTime() + (days*24*60*60*1000));
					var expires = "; expires=" + date.toGMTString();
				}
				else var expires = "";
				document.cookie = name + "=" + value + expires + "; path=/";
			}

			function readCookie(name) {
				var allcookies = document.cookie;
				alert("All Cookies : " + allcookies );

				// Get all the cookies pairs in an array
				cookiearray  = allcookies.split(';');

				// Now take key value pair out of this array
				for(var i=0; i<cookiearray.length; i++){
				  name = cookiearray[i].split('=')[0];
				  value = cookiearray[i].split('=')[1];
				  alert("Key is : " + name + " and Value is : " + value);
				}
			}

			function deleteCookie(name, path, domain) {
				var name = prompt("Which cookie do you want to delete?");
				createCookie(name, "", -1);
			}

			createCookie("cookie1", "derrick", "7");

			var name = "cookie2" ;
			var value = prompt("Please enter your name.");
			var expires = 7 ;

			createCookie(name, value, expires);

		</script>
		<form name="myform" action="">
			<input type="button" value="Get Cookie" onclick="readCookie()"/>
		</form>
		<br>
		<form name="anotherform" action="">
			<input type="button" value="Erase Cookie" onclick="deleteCookie()"/>
		</form>
	</body>
</html>

Excellent in depth article

Leave a Reply