In this article, find out how to store and retrieve persistent data with cookies, small files that allow you to do big things. This article explains the basics of cookies, demonstrates reading and writing them in JavaScript, and illustrates their use in a real-world application.
So that takes care of writing cookies, and then reading the values back. Now, how about a composite example that you can actually use?
In this next example, I'll assume a multi-lingual Web site, where the user has a choice of viewing the content in either French or English. The first time the user visits the site, (s)he is permitted to select one of the two languages. This choice is stored in a cookie, so that on the next visit, the client is automatically redirected to the chosen language without requiring the user to re-select a language.
<html> <head> <script language="JavaScript" src="cookieLibrary.js"></script> <script language="JavaScript"> // check to see if cookie exists // if yes, redirect to language page if (GetCookie("lang") == "EN") { document.location.href="index.en.html"; } else if (GetCookie("lang") == "FR") { document.location.href="index.fr.html"; }
// function to write selected language to cookie function lang(l) { // set expiry date for 1 year from now var d = new Date(); d.setDate(d.getDate() + 365);
// write cookie SetCookie("lang", l, d);
// take user to appropriate language page if (l == "EN") { document.location.href="index.en.html"; } else if (l == "FR") { document.location.href="index.fr.html"; }
That was simple enough. When the user visits the page, the code first checks to see if a cookie with the selected language already exists. If it does, the browser is automatically redirected to pages in that language. If no cookie exists, it implies that the user has not selected a language, and so a language choice is displayed. The language selected is then written to a cookie in preparation for the next visit.