If this page does not print out automatically, select Print from the File menu.

Hands On: How to set and check Javascript cookies

Cookies can be used as an alternative to pop-ups on your website

Nigel Whitfield, Personal Computer World 30 Apr 2008

Previously I've explained how you can use pop-up windows on your website, launching them from a short piece of Javascript.

But, of course, many users aren’t keen on pop-ups, even if they remind them of something quite important.

So it’s a compromise and sometimes part of that compromise might be not displaying a pop-up for a certain amount of time, such as seven days. A solution for handling that is to use cookies.

The cookie monster
Some people have an aversion to cookies, mistakenly believing that they can allow your computer to send private information to a website.

That’s not really the case ­ they can only send back to a website some information that it sent to your computer in the first place, like your user id on the site, or something that helps them see which user has looked at which pages.

A cookie consists of a few bits of data, stored as text on your computer. There’s a name, a value for the data ­ perhaps your id for the site, or a set of preferences, or simply ‘true’ or ‘false’; anything that can be saved as text ­ an expiry date, a path and a domain.

Those last three are the elements that we’re interested in here.

The Expiry date is the date on which the browser can safely discard the cookie. If it’s not set, then the cookie is a ‘session cookie’ which means it’ll disappear when you quit the browser, otherwise it’ll be stored until the date, which is specified in a fairly strict format.

The path restricts the cookie to a section of your website. If it’s set to ‘/’ then the cookie will be returned to the web server for every page on your site. Set it to, say, ‘/shop’ and only pages on your site with URLs starting ‘/shop’ will see its value.

The domain works in a similar way, but can restrict the cookie to part of your domain, or those higher up. If you have a domain mysite.example, then setting the cookie to that would allow it to be seen on websites at forums.mysite. example, or www.mysite.example.

Set it to forums.mysite.example, and the main website won’t get the cookie, either.

Cookies in Javascript
So, now you know how cookies work, how are they handled in Javascript? Not elegantly would be one way of putting it. In a PHP script, and other languages, you can easily see the value of any single cookie. Not so in Javascript.

First, though, how about setting a cookie? All you do is set a value called document.cookie to whatever you want, like this, which sets a cookie called ‘popupshown’ to the value ‘true’:

document.cookie = ‘popupshown=true; expires=Thu, 14 Feb 2007 12:00:00
UTC; path=/’

You could add a domain too ­ it’s just another parameter, which could follow the path option, after a semicolon. Omit the expiry information and you just get a session cookie; set it to a date in the past and you’ll delete the cookie.

And if you wanted to set another cookie, just do the same thing again. ­

You can have lots of cookies on a page and, although it looks as if when you use document.cookie you’re setting a variable, that’s not really the case. ­

You’re telling the browser to set the cookie, and so setting another one with a different name won’t overwrite the first one.

So how do you see cookies? This is where Javascript becomes somewhat less than elegant; document.cookie is a single string, containing all the cookies applicable to the page (based on the domain and path info).

Suppose we’d set another cookie, to indicate a user was an old hand on our site, newuser=false. Put a little code like this in a web page:

document.cookie = ‘popupshown=true; expires=Thu, 14 Feb 2007 12:00:00 UTC; path=/’ ;
document.cookie = ‘newuser=false’ ;
document.write (document.cookie);

What’s sent back is a single string that contains all the cookies, separated by a semicolon, so if you have multiple cookies, you then have to split the string to see which cookies are set.

And, of course, since you use semicolons to separate the options when you create cookies, you have to make sure that you don’t use them for the actual value.

So, you’re going to need a couple of functions to make cookies a little more manageable; first, how about getting that expiry date right?

In Javascript, you can get the current date and time via a Date object ­ in milliseconds since 1 January 1970. Say you want that cookie to expire in seven days time, that’s 7 days x 24 hours x 60 minutes x 60,000 milliseconds.

Object variables in Javascript have ‘methods’ which are like functions, which you append to the variable name, like this, setting the expiry time to seven days from the current one.

expiretime = new Date() ;
expiretime.setTime(expiretime.getTime() + 7*24*60*60000) ;

And we can join two bits of a string together using the + operator, like this:

document.cookie = ‘popupshown=true; expires=’ + expiretime.toGMTString();

After we’ve added this code to a sample page, the highlighted line in the cookie list in our browser shows a date seven days after the page was displayed.

Reading the cookie is a little more challenging; we have to search through the document.cookie value to find the name followed by an equals sign, and then look at everything from there up to the next semicolon.

Here’s one, very basic, way of doing it:

cookiename = ‘popupshown’ ;

if (document.cookie.indexOf(cookiename) != -1 )
{
cookiestart=document.cookie.indexOf(cookiename)+cookiename.length+1 ;

cookieend=document.cookie.indexOf(‘;’,cookiestart-1);

value = document.cookie.substring(cookiestart, cookieend);
} else {
value = ‘not set’ ;
}

document.write(‘<p>Pop up value is ‘ + value + ‘</p>’) ;

There are a couple of new methods in there ­ indexOf searches a string to find where a substring appears, and substring extracts the characters between two points.

There’s little in the way of error checking here, and if you’re using cookies a lot, it’s a better idea to wrap this up into a function, so you can just say something like

value = getCookie(‘popupshown’) ;

but that, as they say, is an exercise for the reader ­ or for one of the many free Javascript libraries on the web.

Using defensive programming
One aspect of web development that’s often overlooked ­ and not just by non-professional site builders ­ is testing.

When you have a straightforward site with just HTML pages, it’s not hard to check that all the links work ­ and your web-editing program may well do it for you.

But when you have scripts, whether Javascript, PHP or anything else, things can be a lot more complicated.

Add a database into the mix and it can become even more important ­ you don’t want to run the risk of people seeing the wrong information, or information relating to another site user.

That’s the sort of mistake that you read about all too often, where an e-commerce site has a flaw that allows users to simply change one element of the URL, and see information about someone else.

Defensive programming is one way to try and help prevent this ­ you can avoid, perhaps, having the site controlled via URLs that include giveaway info, like parameters such as customerid=11234; and where it’s unavoidable, don’t assume that just because you have a customer id set, the correct matching password has also been supplied to get to the page, and so on.

Testing is the other way to check; it might seem very tedious, but if your site uses scripts, and allows users to enter options that take them to other sections, or place orders, or update and view information, then you should ser iously think about writing down a rigorous test script to check that things work properly.

It can start with something as simple as noting down, say, the procedure that you expect someone to follow when they sign up to your site. Write simple instructions, and define what’s a pass or a fail.

For instance: “Enter a username that you know already exists on the sign-up page; pick a password. Click ‘Sign up’. Does the site correctly determine that the name exists, and ask the user to try again?”

And when you’ve tested the things you expect people to do, test the things you might not have thought about; say you have a script that shows the orders a customer has placed.

Include in your script a test for what happens when someone goes straight to that page, so the customer parameter isn’t set, or is set to 0, or to *; do they see nothing? Are they bounced to a login page? Do they see details for all customers’ orders, because you’ve been lazy in the way you search the database?

Thinking of all the different ways things like this might happen can take a long time ­ certainly when you start to include the ways in which people might deliberately try to break your site.

But if you want to be sure your site’s behaving the way it should you’ll probably end up writing a website that’s much harder for people to break. Thankfully, testing can be automated with tools such as iMacros. It’ll still take time, but your site will be more secure as a result.

www.pcw.co.uk/2214392
This article was printed from the Personal Computer World web site
© Incisive Media Ltd. 2008
Incisive Media Limited, Haymarket House, 28-29 Haymarket, London SW1Y 4RX, is a company registered in the United Kingdom with company registration number 04038503
Close this window to return to the website