Previous Page
Next Page

Reading a Cookie

Once you've set a cookie, you'll need to retrieve it in order to do anything useful. The last example set the cookie with the text string "Tom". The very simple Scripts 10.3 and 10.4 show you how to get that value from the cookie and display it on the screen (of course, you normally would not show off your cookies; this script just displays the cookie as an example).

Script 10.3. JavaScript uses the id in this HTML page to insert the cookie result.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <title>I know your name!</title>
     <script language="Javascript"  type="text/javascript" src="script02.js">
     </script>
</head>
<body bgcolor="#FFFFFF">
     <h1 id="nameField">&nbsp;</h1>
</body>
</html>

Script 10.4. This short script reads a previously set cookie and sends it to the document window.

window.onload = nameFieldInit;

function nameFieldInit() {
     if (document.cookie != "") {
        document.getElementById ("nameField").innerHTML = "Hello, " +  document.cookie.
split("=")[1];
     }
}

To read a cookie:

1.
if (document.cookie != "") {



Make sure that the value in the object document.cookie isn't null.

2.
document.getElementById ("nameField").innerHTML = "Hello, " + document.cookie. split("=")[1]);



If the cookie isn't empty, then write a text string (the "Hello," and note the extra space after the comma) and combine it with the split of the cookie value (Figure 10.2).

Figure 10.2. This cookie had my name on it.


Tip

  • Did you notice that you don't need to specify which of the cookies in the cookie file you are reading? That's because a cookie can only be read by the server that wrote it in the first place. The internal cookie mechanisms in the browser won't let you read or write cookies written by someone else. You only have access to your own cookies.



Previous Page
Next Page