Setting and Reading Cookies with JavaScript
The intent of this article is to make setting and reading
cookies with JavaScript an easy thing for you to do.
You'll get two copy 'n paste functions and details about
how to use them. Then, you'll find real world examples
of tracking number of page views, determining how long
a visitor stays on a page, and a rudimentary affiliate
cookie system.
The Two Copy 'n Paste Functions
All the setting and reading is based on the two functions.
They need no editing. Simply copy and paste them into your
web page.
To keep things as simple as I could, the cookie setting and
reading functions assume all cookies are to be available
from any directory of the domain that set them. In other
words, you will not be able to restrict cookies to only
certain directories.
Code to restrict cookies only to secure server connections
is also omitted from the cookie functions.
Put the cookie setting and reading functions anywhere in the
source code of your web page above where they'll be used.
Putting them into the HEAD area is generally a good idea,
but certainly isn't necessary.
Consider putting the cookie functions into an external file
to be inserted automatically into every web page. Then the
functions will be available on any web page you might need
them. (If you decide to use an external file, remove the
first and last lines the SCRIPT and cancel /SCRIPT tags).
How To Use the Cookie Functions
There are two functions, SetCookie() and ReadCookie(). I'll
show you exactly how to use them.
After reading about each of the functions in detail, you'll
find real world examples of use.
The SetCookie() Function
SetCookie() is, of course, used to set a cookie.
You can set as many cookies as you want, so long as the
browser accepts them.
If the browser doesn't accept cookies, you can't force it
to do so. (You can use the ReadCookie() function later to
see if the browser accepted the cookies you set.)
The SetCookie() function is used like this:
SetCookie(NAME, COOKIE, DAYS);
-
Replace NAME with the name for the cookie. You'll
use the same name when you read the value of the
cookie. The name is like an index or pointer to
the location of the cookie in the browser's cookie
database.
The name may contain only letters, numbers and
underscore characters, and it must begin with a
letter.
If you set a cookie with the same name as a previous
cookie set from the same domain, the previous cookie
will be overwritten.
-
Replace COOKIE with the cookie itself. That would be
the value you want stored as the cookie. The cookie
can be composed of any combination of characters.
-
DAYS is optional. If used, replace DAYS with the
number of days the cookie shall last. If DAYS is
omitted, the cookie will last until the browser is
closed. (Of course, the user and other software can
delete the cookie prematurely, which is something
you have no control over.)
The following two lines of JavaScript each set a cookie.
The first line sets a cookie named "William", with
"He's he best!" as the cookie, and lasting for 3000
days. The second line sets a cookie named "Other", with
"Well, maybe" as the cookie, and lasting only until the
browser closes.
That's the simplicity of setting a cookies.
Oh, I should mention that if the cookie contains quotation
marks within it, they need to be escaped with a preceding
backward slash character. Example:
When the above cookie is set, it will overwrite the cookie
with the same name in the previous example. Note that
overwrites can only occur when the cookie is set from a
web page on the same domain as where the previous cookie
was set.
Overwriting a cookie with 0 (or blank) DAYS is a good way
to get rid of cookies previously set. Once overwritten,
they will disappear when the browser closes.
In this example, a cookie is set with a username to last
a year.
And, in this example, that same cookie is overwritten with
junk data to be deleted when the browser closes.
The reason a period is used as the cookie instead of no
characters (an empty cookie) is because at least one
browser won't set the cookie if it is empty. The cookie
doesn't have to be a period, any character or characters
may be used. When removing cookies, the idea is to set
a non-empty cookie with, when security is a concern, a
value different than the previous cookie.
The ReadCookie() Function
ReadCookie(), you realize immediately, is used to read
a cookie.
You can read any cookies that have been set with the
SetCookie() function, provided they are being read on
the same domain they were set at.
The ReadCookie() function is used like this:
ReadCookie(NAME);
Replace NAME with the name of the cookie you want
to see. If a cookie by the name you specify does not
exist, the function will return a null string (a
string containing no characters and with a length of
zero).
The cookie that the ReadCookie() function returns can be
stored in a variable and used for display, in calculations,
and/or for comparing with other variables.
The following two lines read the "William" cookie and then
display it in an alert box:
The variable name "acookie" can be changed to any other
variable name, instead.
The next three lines check whether or not the "Other"
cookie exists and display an alert accordingly.
If the above is used to check whether or not the browser
accepted a cookie set earlier, the cookie absent alert
might nudge the visitor to turn cookies on. Something like
this:
The Real World Examples
Now you know the basics of using the SetCookie() and
ReadCookie() functions. Lets have a look at some real
world examples of use.
With all of the examples, the cookie name may be changed,
provided both SetCookie() and ReadCookie() specify the same
cookie name (when the example uses both of those functions).
Each of these examples mention logging as an option.
The
recent "Logging Page Activity" blog post
contains how-to information about how to use JavaScript in
conjunction with CGI Perl or PHP to log web page activity or
events.
The second and last real world examples in this article
contain an actual logging implementation that uses the
Perl script obtained from the above blog post.
Tracking Number of Page Views
This will count how many page views on your domain the
visitor has experienced.
The JavaScript will need to be on each web page in the
count. If any web page views are not to be counted, simply
omit the JavaScript from those pages.
Put this JavaScript in the HEAD area of each web page
source code that are to be counted, below the SetCookie()
and ReadCookie() functions. Customization notes are below
the JavaScript:
Customizations:
-
A DAYS parameter can be added to the SetCookie()
function to remember and increment the count over
a span of days.
-
The number 25 on the last line can be a different
number.
-
The alert message may be changed.
-
The alert message may be replaced with a different
action redirect to different page, logging the
event, opening email program with pre-filled body
text are some examples.
A lot of things get done in those few lines of JavaScript.
Logging Length of Time On Web Page
This will track how long a site visitor remains on a web
page. When the visitor leaves the page, the number of
seconds elapsed between when the page loaded and when
the visitor left the page is written to a log file. (The
Perl CGI script that updates the log file is found at the
"Logging Page Activity" blog post.)
To implement, put this JavaScript in the HEAD area of the
web page source code, below the SetCookie() and ReadCookie()
functions:
The above updates a tab-delimited log file. The file can be
imported into spreadsheets for averaging. In the usual case,
the longer visitors stay on a page, the more interesting or
targeted the page contents were perceived to be.
Trigger Event If Time on Page Exceeds Specific Period
Display a message (related pages list, for example) if a
visitor stays on a page longer than a certain time.
This will display an alert box message if the visitor's
time on the web page exceeds a specific number of seconds.
To implement, put this JavaScript in the HEAD area of the
web page source code, below the SetCookie() and ReadCookie()
functions. Customization notes are below the JavaScript:
Customizations:
-
The number 25 on the alert line can be a different
number.
-
The alert message may be changed.
-
The alert message may be replaced with a different
action redirect to different page, logging the
event, opening email program with pre-filled body
text are some examples.
This one has a lot of possibilities a product discount
for demonstrating such interest, a list of suggested
similar articles, complementary web sites links, for
examples.
A Rudimentary Affiliate Cookie System
This system assumes affiliates get paid per ezine sign-up.
This real world example can work for pretty much any site
where affiliates get paid or credited a certain amount per
action. This might be sale of an ebook, free membership
sign-up, clicking on a banner, whatever.
JavaScript on the sales page sets a cookie.
JavaScript on the "thank you" or confirmation page looks
for the cookie and, if found, logs the cookie value.
Thus, when an affiliate sends a prospect to the sales page
with a certain link, the affiliate ID is recorded as a
cookie. If a previous affiliate cookie existed on that
particular prospect's browser, it is overwritten with the
new one.
To work with this system, the URL of the link must be
followed by a question mark and the affiliate ID. Here
are two example affiliate links:
http://example.com/?AffID
http://example.com/shoes.html?AffID
Should the prospect sign up, buy, or otherwise take an
action that causes the "thank you" or confirmation page
to load into the prospect's browser, the affiliate ID
cookie is read and logged.
Note that the cookie name in the JavaScript of both the
sales page and the "thank you"/confirmation page must be
exactly the same name.
To enable the sales page, put these 5 lines of JavaScript
in the HEAD area of the web page source code, below the
SetCookie() and ReadCookie() functions:
Change the DAYS to the number of days the cookie shall last
on the prospect's browser.
To enable the "thank you"/confirmation page, put these 5
lines of JavaScript in the HEAD area of the web page source
code, below the SetCookie() and ReadCookie() functions:
The Perl CGI script that updates the log file is found at the
/blog/automation/Logging_Page_Activity.html
"Logging Page Activity" blog post.
Making it Easy
The way to make this JavaScript easy is to just do it. Copy
the code and paste it into a web page and see what happens.
The more experience you get, the easier it becomes.
The Firefox browser
is an excellent JavaScript debugging tool. Load the problem
page into the browser, select menu item "Tools" and then
"JavaScript Console." It will list any errors it found, with
line number and even the character position of the error if
it can be determined.
Using a good debugging tool and having joy of seeing what
happens when this or that is done is a good way to learn
and become at ease.
Enjoy :)
Question:
Did you find this article interesting and understandable? How can it be improved?
Your response is anonymous.
When done typing, click anywhere outside the box. [more info]
Will Bontrager
©Copyright 2006 Bontrager Connection, LLC Bontrager Connection, LLC
Please note:
Articles on this website are presented "as is". However -
If you have a question about a CGI script, HTML, CSS, PHP, or JavaScript
Ask one of our Experts and you'll have your answer!
Click here for details.