Categories:
Partners

Setting and retrieving a cookie

One property alone carries the burden of realizing session-only cookies in JavaScript:

document.cookie   Read/write property that stores and persists data in a semicolon (;) delimited format

Think of document.cookie as the familiar variable, but with a twisted, persistent personality: Below we store a string into it, and examine what comes out:

document.cookie="JavaScript Kit"
alert(document.cookie) 

You should see 1 of 3 things get alerted- 1) "JavaScript Kit", 2) A string containing multiple values, one of which is "JavaScript Kit", or 3) A blank string. Note that if you see nothing (blank string), your browser does not have cookies enabled (hint: change that!).

document.cookie is a "public facility", with its usage shared by all scripts on all sites that access it. Due to this, the property often contains more values than you had stored into it, the other values being from other sites. When this is the case, each value is separated by a semicolon. All of these values are persisted until the browser is closed.

Retrieving data from the cookie

Ok, so everyone can take a bite out of document.cookie; how do you locate your piece and grab it? Herein lies the bulk of your work when working with session only cookies- retrieving what was put into it.

The following 2 steps are involved in most techniques used to get your data out of a session cookie:

1) Store your data using a name/value pair format
2) Use string methods such as string.indexOf() and string.split() to scan for/retrieve this data

For example:

//store data using name/value format
document.cookie="sitename=JavaScript Kit" 

//retrieve value from cookie
var beginindex, endindex, result
//set begin index to 1st letter of value ("W")
beginindex=document.cookie.indexOf("sitename")+9
endindex=beginindex
//while we haven't hit ";" and it's not end of cookie
while (document.cookie.charAt(endindex)!=";"&&
endindex<=document.cookie.length)
endindex++
//result contains "JavaScript Kit"
var result=document.cookie.substring(beginindex,endindex) 

Quite a mess, all the reason to read on...

-Get cookie routine

If there's a time to forgo your ego and use premade JavaScript libraries, it's when working with cookies. Read up on the subject in most JavaScript books, and you'll find the same recommendation.

With respect to the topic at hand- retrieving data from a cookie- an excellent prebuilt routine to use is the following:

Shelley Power's get cookie routine:

With it in place, to extract your data from document.cookie, simply input the data's name as parameter:

var result=get_cookie("sitename") 

Should the corresponding value not exist, the routine returns an empty string.

p.s: See here for a complete JavaScript cookie library.

We now know how to both store and retrieve data from a session-only cookie. But what good is that?

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.