Session Handling Using Cookies
2. document.cookie
2.1. A web page with cookies
Let’s try creating a webpage that makes use of cookies. For this example, we will create a web page that asks for the name of the user. The next time the user visits the page, a welcome message with the user’s name is displayed.
The code below has three main functions. Each function has a specific role in setting up the values of cookies. They are listed as follows:
1. setCookie(varKey, varValue)
This is used to initialize the values of the cookie. The example belowinitializes a string that has a format "<varKey> = <varValue>".
Note that the < > symbols means that they are placeholders. The quotation marks are used to indicate that the values are strings.
Let’s say that you want the function to accept a cookie for a username. The varKey variable will store “username” because it is the “key,” so to say, to the actual value of the username. The value of the cookie will now look like this:
document.cookie = "username = ThisUserName";
3. checkCookie()
<!DOCTYPE html>
<html>
<head>
<script>
// this function is called from checkCookie()
function setCookie(varKey,varValue) {
// saving actual cookie
document.cookie = varKey + "=" + varValue;
}
/* This function is called from checkCookie() as well, in this getCookie() function, the username is derived by splitting the string stored in the cookie. Each key-value pair is separated by semicolons. Then the key and value are separated by equal signs. */
function getCookie(varKey) {
var key = varKey + "=";
var retrieveCookie = document.cookie;
var ca = retrieveCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(key) == 0) {
return c.substring(key.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
