"Everybody is a genius. But if you judge a fish by its ability to climb a tree, it will live its whole life believing that it is stupid." – Albert Einstein

Difference: session & Cookie


Cookies persist on your local computer, they are small text files that are stored there by websites and web applications that contain some basic information about you as a user.

Sessions are application specific and persist only as long as you are actively engaged with a particular web site. For instance if you leave Amazon.com open do some shopping, then close the web browser before making any purchases, your session has ended, however the cookie that identifies your username still exists on your local computer.

Session-only cookies
Preheat your oven people, for the time has come to thrust JavaScript into it until some long term memory develops. In this tutorial, we’ll look up the recipe for session-only cookies, and how they can help your scripts retain information even after the page is reloaded or cleared.

Brief overview
JavaScript cookies are the vehicle to persisting data between client requests. When a site requiring login remembers your username on return visits, for example, thank not Oreos, but these uneatable imposters.

There are two types of JavaSript cookies- permanent, and session-only. The first one stores its information in a physical file on the client’s computer called “cookie.txt”, with the stored data “permanently” available. Session only cookies, on the other hand, stores information in the browser memory, and is available for the duration of the browser session. In other words, the data stored inside a session cookie is available from the time of storage until the browser is closed. Moving from page to page during this time does not erase the data.

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 0) {
offset = document.cookie.indexOf(search)
// if cookie exists
if (offset != -1) {
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(“;”, offset);
// set index of end of cookie value
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

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.

Example
Session cookies’ finest hours often occur behind the scenes, and as part of a larger equation. Inter-page surveys or popup-once windows are classic examples of this.

With that in mind then, here is a crude demonstration whereby the user can customize the color of the document’s background, with this color then applied to all pages on the site:

Demo:

Select background color Light gray Sky blue Purple White

Source:

//Get cookie routine by Shelley Powers
function get_cookie(Name) {
var search = Name + “=”
var returnvalue = “”;
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
// if cookie exists
if (offset != -1) {
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(“;”, offset);
// set index of end of cookie value
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function setcolor(what){
document.body.style.backgroundColor=what
document.cookie=”bgcolor=”+what
}

if (get_cookie(“bgcolor”)!=””)
document.body.style.backgroundColor=get_cookie(“bgcolor”)

Select background color
Light gray
Sky blue
Purple
White

Try reloading or navigating away then back to this page; the selected background color persists. To extend this persistence to all pages on your site, you would simply include the get_cookie routine and the two lines of code that set the document’s background on these pages. Here is an additional page to illustrate this.

2 responses

  1. manish

    The part i.e Live Traffic feed is very intresting & secondly the flag counter

    January 7, 2010 at 5:41 PM

  2. VanBCGunner

    I don’t think you can read other site’s cookie in document.cookie otherwise, that could be a greate security breach…

    February 14, 2009 at 12:20 AM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s