Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryCookies and Browser Interaction

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Setting and Reading Cookies with JavaScript

Addition: Cookies should be set with the "secure" flag whenever a cookie is set from a web page with a secure connection (https:// vs. http://). The "https://www.willmaster.com/library/web-development/setting-secure-cookies.php library article talks about how to set a secure cookie with JavaScript and with PHP.

The intent of this article is to make setting and reading cookies with JavaScript an easy thing for you to do.

See also Setting and Viewing Cookies with PHP .

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.

<script type="text/javascript" language="JavaScript">
<!-- Copyright 2006 Bontrager Connection, LLC
// Published on October 31, 2006 for Possibilities 
//   ezine. See https://www.willmaster.com/ article titled 
//   "Setting and Reading Cookies with JavaScript."
//
////
//
// These functions set and read cookies. See article 
//   mentioned above for information and instructions.
//
////  ////  ////  ////

function SetCookie() {
if(arguments.length < 2) { return; }
var n = arguments[0];
var v = arguments[1];
var d = 0;
if(arguments.length > 2) { d = parseInt(arguments[2]); }
var exp = '';
if(d > 0) {
	var now = new Date();
	then = now.getTime() + (d * 24 * 60 * 60 * 1000);
	now.setTime(then);
	exp = '; expires=' + now.toGMTString();
	}
document.cookie = n + "=" + escape(String(v)) + '; path=/' + exp;
} // function SetCookie()

function ReadCookie(n) {
var cookiecontent = new String();
if(document.cookie.length > 0) {
	var cookiename = n+ '=';
	var cookiebegin = document.cookie.indexOf(cookiename);
	var cookieend = 0;
	if(cookiebegin > -1) {
		cookiebegin += cookiename.length;
		cookieend = document.cookie.indexOf(";",cookiebegin);
		if(cookieend < cookiebegin) { cookieend = document.cookie.length; }
		cookiecontent = document.cookie.substring(cookiebegin,cookieend);
		}
	}
return unescape(cookiecontent);
} // function ReadCookie()
// —>
</script>

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);
  1. 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.

  2. 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.

  3. 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.

<script type="text/javascript" language="JavaScript"><!--
SetCookie("William", "He's the best!", 3000);
SetCookie("Other", "Well, maybe");
// —></script>

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:

<script type="text/javascript" language="JavaScript"><!--
SetCookie("Other", "They decided \"never\" to do it.");
// —></script>

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.

<script type="text/javascript" language="JavaScript"><!--
SetCookie("Mari", "chocolate", 365);
// —></script>

And, in this example, that same cookie is overwritten with junk data to be deleted when the browser closes.

<script type="text/javascript" language="JavaScript"><!--
SetCookie("Mari", ".");
// —></script>

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:

<script type="text/javascript" language="JavaScript"><!--
var acookie = ReadCookie("William");
alert(acookie);
// —></script>

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.

<script type="text/javascript" language="JavaScript"><!--
var acookie = ReadCookie("Other");
if(acookie.length == 0) { alert('It does not exist.'); }
else { alert('It exists!'); }
// —></script>

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:

<script type="text/javascript" language="JavaScript"><!--
var acookie = ReadCookie("Other");
if(acookie.length == 0) { alert('Turn cookies on!'); }
// —></script>

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).

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:

<script type="text/javascript" language="JavaScript"><!--

// Read cookie for previous count.
// Determine new count by adding number 1 to cookie.
// Make new cookie with new count and set it.
var previouscookie = ReadCookie("PageViews");
var newcookie = 0;
if(previouscookie.length == 0) { newcookie = 1; }
else { newcookie = parseInt(previouscookie) + 1; }
SetCookie("PageViews", newcookie);

// Do something if number of page views reaches 25.
if(newcookie == 25) { alert('Thank you, loyal reader!') ; }

// —></script>

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.

To implement, put this JavaScript in the HEAD area of the web page source code, below the SetCookie() and ReadCookie() functions:

<script type="text/javascript" language="JavaScript"><!--

// Establish an entry time.
var t = new Date();
var beginmilliseconds = t.getTime();
SetCookie("TimeOnPage", beginmilliseconds);

// The time elapsed logging function.
function LogElapsedTime() {
var tt = new Date();
var nowmilliseconds = tt.getTime();
var elapsedseconds = nowmilliseconds - beginmilliseconds;
elapsedseconds = parseInt(elapsedseconds / 1000);
view = new Image();
view.src = '/cgi-bin/Log.cgi?'+elapsedseconds+'%09seconds';
} // function LogElapsedTime()

// Set LogElapsedTime() to run when page unloads.
window.onunload = LogElapsedTime;

// —></script>

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:

<script type="text/javascript" language="JavaScript"><!--

function GetStarted() {
var t = new Date();
var beginmilliseconds = t.getTime();
SetCookie("TimeOnPage", beginmilliseconds);
PeekAtElapsedTime();
} // function GetStarted()

// See how much time has passed.
function PeekAtElapsedTime() {
var start = ReadCookie("TimeOnPage");
var tt = new Date();
var nowmilliseconds = tt.getTime();
var elapsedseconds = nowmilliseconds - start;
elapsedseconds = parseInt(elapsedseconds / 1000);
// Do something if number of seconds exceeds 25.
if(elapsedseconds > 25) { alert('A loyal reader!') ; }
else { setTimeout('PeekAtElapsedTime()',1000); }
} // function PeekAtElapsedTime()

// Get things started.
GetStarted();

// —></script>

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 websites 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
https://example.com/shoes.php?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:

<script type="text/javascript" language="JavaScript"><!--
var questionlocation = location.href.indexOf('?');
if(questionlocation > 0) {
   AffiliateID = location.href.substr(questionlocation + 1);
   SetCookie("ID", AffiliateID, 90);
   }
// —></script>

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:

<script type="text/javascript" language="JavaScript"><!--
var AffiliateID = ReadCookie("ID");
if(AffiliateID.length > 0) {
	view = new Image();
	view.src = '/cgi-bin/Log.cgi?'+AffiliateID;
	}
// —></script>

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 :)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC