Saving Client State with Cookies and Java - Throwing JavaScript Into the (Cookie Dough) Mix
(Page 5 of 6 )
Since our cookies are stored on our client, our client Internet browser can access them using JavaScript. We do just that in the file grabcookievaluewithjavascript.html whose code is shown in Listing 3 below.
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM WebSphere Studio">
<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="theme/Master.css" rel="stylesheet" type="text/css">
<TITLE>JavaScript Cookie Demo</TITLE>
<SCRIPT language="JavaScript">
<!--
function GetCookieValue(offset)
{
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
document.write(document.cookie.substring(offset, endstr));
return unescape(document.cookie.substring(offset, endstr));
}
function ReportCookieValue (cookieName)
{
var arg = cookieName + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen)
{
var j = i + alen;
var sub = document.cookie.substring(i,j);
if (sub == arg)
{
return GetCookieValue(j);
}
else i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<p></p>
<h2>According to JavaScript, you like <script language="JavaScript">
<!--//ReportCookieValue("FavoriteCookieType")//-->
</script> Cookies .</h2>
<p></p>
</BODY>
</HTML>
Listing 3: grabcookiewithjavascript.html
The output of our JavaScript cookie extraction is shown below:

Figure 6: Extracting our Cookie Value on the Client via JavaScript
Being able to access your cookies via JavaScript represents a powerful functionality. By doing this, you can have forms preloaded with what is resident in client cookie data. As an exercise, you should try and modify favoritecookie.html to initially present the pull down value that was resident in your cookie.
Next: Cleaning Up: Getting Rid of Cookie Crumbs >>
More Java Articles
More By Kulvir Singh Bhogal