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).

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 ...

Get JavaScript and Ajax for the Web: Visual QuickStart Guide, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.