School of Computing  |  Napier  |  Cisco  |  SFC  |  NOS  |  Code |  Old page


JavaScript - Cookies

The following tables shows a few simple examples of how a cookie is stored, read-back and deleted:

HTML/JavaScript

Executed Code

Storing a cookie: A cookie is stored in JavaScript by setting the cookie property of the document object (with document.cookie). This then defines the properties of the cookie, such as the date that it expires, and the domain of the WWW page. These are defined in keyword pairs which are seperated by semi-colons (;).

This cookie produces a text file in the \WINDOWS\COOKIES directory with the name of user@wwwsite.txt. The contents will be:

bills
1234
localhost/
1088
1553936640
30173035
2771961120
29438780
*

<script language="Javascript">

function SetCookie (name,value,expires,domain) {
var str;
 document.write("Writing cookie...");
 str=name + "= " + value + "; expires=" +  expires.toGMTString() + ";domain="+domain;
 document.write("<" + str + ">");
 document.cookie = str;
}
var expdate = new Date ();
 expdate.setTime (expdate.getTime() + (10 * 365 *   24 * 60 * 60 * 1000)); // 10 years from now
 SetCookie("bills", 1234,expdate , ".napier.ac.uk")
}
</script>

Reading the values of a cookie: The cookie is read in keyword pairs.

 


<script language="Javascript">
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
 if (endstr == -1)
  endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset,   endstr));
}
</script>

Reading a cookie: The property values in the cookie are defined as name and value. In this case the cookie is read back and the value is displayed. If a cookie is stored then the value displayed is "1234".

 

<script language="Javascript">
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
 while (i < clen) {
  var j = i + alen;
  if (document.cookie.substring(i, j) == arg)
    return getCookieVal (j);
  i = document.cookie.indexOf(" ", i) + 1;
  if (i == 0) break;
 }
 return null;
}
 str=GetCookie("bills");
 document.write("Cookie is ", str);
</script>

Deleting a cookie: A cookie can be deleted by making it expire in a date defined before the current date. In this case the date is set at 1970. The browser automatically deletes any cookies which have expired. I won't delete the cookie, as you can have a look for it on your own computer (too see what it looks like).

 

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

 

School of Computing  |  Napier  |  Cisco  |  SFC  |  NOS  |  Code |  Old page

Page maintained by bill