Cookies
<font color="red" size=4>WebTV JS "Bug" - Reload Page (cmd-r)</font>

If an array is created the content of the array will reside on the page and can be accessed when the program is run. However, additons to, deletions of, or modifications in the array elements must be done by editing the code for the page. A server-side, but not a client-side task. On the other hand, a constructor function can be used to make an object the properties for which can be selectively placed in an array, and this can be done by a client or user. However, this applies to only one object and whatever information is entered is lost when the page is exited. Something is needed that will allow the accumulation of the properties for many objects, as with grades for every student in a classroom, and which will readily allow a user to access and modify each record. With PC users and web servers this something is a storage device, such as a hard-disk. For clients using JS the browser itself is often used as a storage device. Limited amounts of bits of information, called cookies, can be maintained in users browsers, and these cookies can have their content modified as desired.

Cookie Recipe  With JS everything has a separate name, and so does a cookie. With a cookie, though, it is a name=value pair that makes it up. The name is its identifier and the value the cookie content. Just like saying, Macaroons and not chocolate chip". So, to start making a cookie, say what kind:

document.cookie=name+"="+escape(value);


This is a standard format for assigning a "name=value" pair. An expiration date as well as other parameters can follow these. A name will not initially be assigned to a cookie in this discussion and, since expiration dates will not be included in any cookies defined, the cookies will disappear upon exiting this page. The mechanics of dealing with a cookie will first be considered.

In the simplest possible terms, the value of a cookie is a string consisting of all items making up a record, i.e., names and values, and is stored using the statement:

document.cookie=recrd;


The information stored is called by reversing the statement

recrd=document.cookie;


Seems simple enough, excepting problems come with storing records as a string. Names have spaces and a delimiter, i.e., a symbol like a comma or a semi-colon, has to be used to designate where one record ends and another begins.

Filling in of spaces is done using the escape function prior to putting the string in a cookie:

recrd=escape(recrd);


This is done to introduce a code to identify where a space is, otherwise the string would collapse into the places occupied by spaces. Retrieving the string by removing the space-code is accomplished by an unescape function

recrd=unescape(recrd);


Clicking on the example button below shows the operation of these functions:



The coding given below is for a very simple example. The page containing a cookie code must be published to determine if a cookie has been created (With thanks to WbWzrd for pointing this out. It will not work otherwise using Preview mode in WebTV's Page Builder):



The example is arranged to show that the cookie is available directly upon being set. It can also be accessed by reloading this page. This is a session cookie, though, and will be lost upon exiting this page. More than one cookie can be made provided each is given a different name. The name for the example cookie is fixed.



It will be noted that some machine related codes have been appended and follow a semi-colon ( ; ). If, however, the name entered was followed by a colon ( : ) when stored in the cookie, upon using the split function the machine code would have been separated out and not shown in the alert. Alternatively, an IndexOf function could be used in association with a substring function:

pos=crumb[1].IndexOf(";");
crumb[1]=crumb[1].substring(0,pos);/td>


The IndexOf function provides the number of characters, pos, up to and including the referenced symbol, counting from left-to-right. Using this value in a substring function isolates just the essential data element.

"Crumbling" Cookies  Information, when it is input, always is in a JS string variable. All that is being done with escape functions is making sure the string contains all the spaces it is supposed to have. The more difficult part is in extracting the data. Since the information is contained in a long string the cookie will have to be "crumbled", i.e., taken apart, to have access to each piece of data. For this it has to be decided beforehand how to delimit the data entered, for that will determine the nature of the routine that will contain the cookie "crumbs", i.e., each data item.

For example, say that a person's name, e-mail address, and telephone number are to be put in a cookie. Beforehand it is decided that the most appropriate way to enter the data is to separate each query by a slash and each reponse by a colon. The cookie string will then look like this :

var person="Name:Joe E. Burn/e-Mail:sepia@WebTV.com/ Ext:666";


In this form an associative array can be used to easily access any data item. However, this cookie must be "crumbled" to be able to do so. First the cookie string must be separated from its identifier, "person". The split function will do this when the delimiter is the equals sign. It will be remembered that the split function creates array elements, so the identifier will be in array element 0 and the value string in array element 1:

var crumb=person.split("=");
var thevalues=crumb[1];


One way to create an associative array from the values string is to first determine how many data elements there are by splitting the value string:

indvals=thevalues.split("/");nindvals=indvals.length


Then each element in turn must be further split, one part becoming the associative array index and the other its value:

for(i=0; i < nindvals; i++>
{temp=indvals[i].split(":");
tindex=temp[0];
tvalue=temp[1];
reprt[tindex]=tvalue;}


This leads to the associative array as defined by the statement:

var reprt=new Array();


the elements for which would be:

reprt["Name"]="Joe E. Burn"
reprt["e-Mail"]="sepia@web.com";
reprt["Ext"]="666"


On Making Cookies  Within a user's browser there should be a file called "cookies". Not all browsers will have one, and those that have may be restrictive in its use. This file can contain two types of cookies. One type, a "persistent cookie", is "implanted" by a server and has an expiration date of when to clear itself from a visitor's browser. These are passed to a users browser whenever certain sites are visited. They do nothing other than record how frequently that particular site is visited, and are not accessible from other sites. Very few cookies are allowed per user's (visitor's) browser, so when the limit is reached and a new cookie is inserted an older one is automatically discarded.

The other kind of cookie is a "session cookie". These are intended to remain active only as long as the browser is on. Turning off the browser erases the cookie. It is this kind of cookie that is often included a page when performing certain tasks requiring information storage. For example, items may be selected and put into a "shopping cart", a cookie, and the selection tallied upon request.

A cookie can be made to be either "persistent" or "session-only" by inclusion or omission of an expiration date, i.e., the cookie is defined by:

document.cookie=
name+escape(value)+";expires="+expdate;


The expiration date is entered at a point before the cookie definition and is set as follows:

var dateset=new Date("Month Day, Year");
expdate=dateset.toGMTString();


The Month, Day, and Year are chosen as desired. Making the day as the day before today erases the cookie. For any other date, the cookie will disappear on that date. The toGMTString function puts in the day, Sun through Mon, that the date falls on.

For example, say an expiration date of one month is desired. This is set by multiplying 1000 milliseconds by 60 seconds by 60 minutes by 24 hours by 31 days. If you want to save the cookie for a year change the 31 to 365.

There are a number of other parameters that may be used in setting a cookie. When used they must be in the following order:
  • name - The cookie's. name.value - The cookie's value.
  • [expires] - Expiration date for the cookie. Omitted or null expires at the session end.
  • [path] - Sets top level directory from which a cookie can be read. For path=/ all pages in the directory can read the cookie. Omitted or null the path is the existing document.
  • [domain] -Indicates domain where the cookie is valid. Omitted or null the domain of the calling document is used.
  • [secure] - True or false value indicating if cookies requires a secure channel.
With all parameters utilized the cookie definition becomes:

document.cookie=
name+"="+value"+";expires="+dateset.toGMTString()+
";path="+path+";domain="+domain+";true/false";


It should be noted that all optional parameters are preceded by a semi-colon.

Custom Cookies  In summary, there are three requisites for working with cookies:
          • Get a cookie, if presentSet a cookie.
          • Delete a cookie.
What is to be done with the stored value depends on intent, and for this it is up to the programmer to devise their own routine to achieve the desired result. Alternatively, cookie codes may be obtained from free script sources. The codes given below are in the public domain and may be used to fetch, create, and delete cookies:



JS Test-Bed 1 - - JS Test-Bed 2


<< PreviousNext>>