JavaScript DHTML/Development/Cookie

Материал из Web эксперт
Перейти к: навигация, поиск

A Cookie Example

  
/*
JavaScript Unleashed, Third Edition
by Richard Wagner and R. Allen Wyke 
ISBN: 067231763X
Publisher Sams CopyRight 2000
*/
<html>
<head>
<script language="JavaScript">
<!-- Comment out script from browsers that don"t know JavaScript
   
//===============================================================
// Here are our standard Cookie routines
//===============================================================
//---------------------------------------------------------------
// GetCookie - Returns the value of the specified cookie or null
//             if the cookie doesn"t exist
//---------------------------------------------------------------
function GetCookie(name)
{
  var result = null;
  var myCookie = " " + document.cookie + ";";
  var searchName = " " + name + "=";
  var startOfCookie = myCookie.indexOf(searchName);
  var endOfCookie;
  if (startOfCookie != -1)
  {
    startOfCookie += searchName.length;
    // skip past cookie name
    endOfCookie = myCookie.indexOf(";", startOfCookie);
    result = unescape(myCookie.substring(startOfCookie,endOfCookie));
  }
  return result;
}
   
//---------------------------------------------------------------
// SetCookieEZ - Quickly sets a cookie which will last until the
//               user shuts down his browser
//---------------------------------------------------------------
function SetCookieEZ(name, value)
{
  document.cookie = name + "=" + escape(value);
}
   
//---------------------------------------------------------------
// SetCookie - Adds or replaces a cookie. Use null for parameters
//             that you don"t care about
//---------------------------------------------------------------
function SetCookie(name, value, expires, path, domain, secure)
{
  var expString = ((expires == null)? "" : ("; expires=" + 
                    expires.toGMTString()));
  var pathString = ((path == null) ? "" : ("; path=" + path));
  var domainString = ((domain == null)? "" : ("; domain=" + domain));
  var secureString = ((secure == true) ? "; secure" : "");
  document.cookie = name + "=" + escape(value)+ expString + pathString + 
                domainString+ secureString;
}
   
//---------------------------------------------------------------
// ClearCookie  - Removes a cookie by setting an expiration date
//                three days in the past
//---------------------------------------------------------------
function ClearCookie(name)
{
  var ThreeDays = 3 * 24 * 60 * 60 * 1000;
  var expDate = new Date();
  expDate.setTime (expDate.getTime() - ThreeDays);
  document.cookie = name + "=ImOutOfHere; expires="+ expDate.toGMTString();
}
   
//===============================================================
// Here are the object and the routines for our Favorites app
//===============================================================
//---------------------------------------------------------------
/* Here is our "favorite" object.
   Properties: fullName - The full descriptive name
               cook     - The code used for the cookie
               urlpath  - The full url (http://...) to the site
      Methods: Enabled - Returns true if the link"s cookie is
                         turned on
               Checked  - Returns the word "CHECKED" if the
                          link"s cookie is turned on
               WriteAsCheckBox - Sends text to the document in a
                                 checkbox control format
               WriteAsWebLink  - Sends text to the document in a
                                 <a href...> format
---------------------------------------------------------------*/
function favorite(fullName, cook, urlpath)
{
  this.fullName = fullName;
  this.cook   = cook;
  this.urlpath  = urlpath;
  this.Enabled = Enabled;
  this.Checked = Checked;
  this.WriteAsCheckBox = WriteAsCheckBox;
  this.WriteAsWebLink = WriteAsWebLink;
}
   
//---------------------------------------------------------------
// Enabled - Checks to see if the cookie exists
// returns - true if the cookie exists
//           false if it doesn"t
//---------------------------------------------------------------
function Enabled()
{
  var result = false;
  var FaveCookie = GetCookie("Favorites");
  if (FaveCookie != null)
  {
    var searchFor = "<" + this.cook + ">";
    var startOfCookie = FaveCookie.indexOf(searchFor);
    if (startOfCookie != -1)
      result = true;
  }
  return result;
}
   
//---------------------------------------------------------------
// Checked - Checks to see if the cookie exists (using Enabled)
// returns - "CHECKED " if the cookie exists
//           "" if it doesn"t
//---------------------------------------------------------------
function Checked ()
{
  if (this.Enabled())
    return "CHECKED ";
  return "";
}
//---------------------------------------------------------------
// WriteAsCheckBox - The favorite may be either a regular URL or
//                   a section title.  If the urlpath is an empty
//                   string, then the favorite is a section title.
//                   The links will appear within a definition
//                   list, and are formatted appropriately.
//---------------------------------------------------------------
function WriteAsCheckBox ()
{
  // Check to see if it"s a title or regular link
  if (this.urlpath == "")
  {
    // It"s a section title
    result = "<dt><strong>" + this.fullName + "</strong>";
  }
  else
  {
    // It"s a regular link
    result = "<dd><input type="checkbox" name=""+ this.cook + "" "+ 
                this.Checked()+ "onClick="SetFavoriteEnabled(this.name, 
                this.checked);">"+ this.fullName;
  }
  document.write(result);
}
   
//---------------------------------------------------------------
// Global Variable:
// NextHeading - Sometimes we only want to print a heading if one
//               its favorites is turned on.  The NextHeading
//               variable helps us to do this. See WriteAsWebLink
//---------------------------------------------------------------
var NextHeading = "";
   
//---------------------------------------------------------------
// WriteAsWebLink - The favorite may be either a regular URL or
//                  a section title.  If the urlpath is an empty
//                  string, then the favorite is a section title.
//                  The links will appear within a definition
//                  list, and are formatted appropriately.
//---------------------------------------------------------------
function WriteAsWebLink()
{
  var result = "";
  if (this.urlpath == "")
  {
    NextHeading = this.fullName;   // It"s must be a Title
  }
  else
  {
    if (this.Enabled() || (GetCookie("ViewAll") == "T"))
    {
      if (NextHeading != "")
      {
        result = "<p><dt><strong>" + NextHeading+ "</strong>";
        NextHeading = "";
      }
      result = result + "<dd><a href="" + this.urlpath + "">"+ this.fullName +
                    "</a>";
    }
  }
  document.write(result);
}
   
//===============================================================
// Global Variables
//===============================================================
/*---------------------------------------------------------------
FaveList will be a list of all favorite objects, which are
then declared below.  favorites with an empty urlpath property
are section headings
---------------------------------------------------------------*/
var FaveList = new Array();
// Comics Section -------------------
FaveList[1] = new favorite("Comics", "", "");
FaveList[2] = new favorite("Dilbert", "cdilb",
Image from book "http://www.unitedmedia.ru/comics/dilbert/");
FaveList[3] = new favorite("Doonesbury", "cdoon",
Image from book "http://www.uexpress.ru/cgi-bin/ups/mainindex.cgi?code=db");
FaveList[4] = new favorite("Mr. Boffo", "cboff",
Image from book "http://www.uexpress.ru/cgi-bin/ups/new_mainindex.cgi?code=mb");
// General News Section -------------
FaveList[5] = new favorite("General News", "", "");
FaveList[6] = new favorite("CNN", "ncnn", "http://www.cnn.ru/");
FaveList[7] = new favorite("NPR", "nnpr","http://www.npr.org/news/");
FaveList[8] = new favorite("Boston Globe", "nbos","http://www.boston.ru/");
// Computer Industry Section --------
FaveList[9] = new favorite("Computer Industry", "", "");
FaveList[10] = new favorite("PC Week", "ipcw","http://www.pcweek.ru/");
FaveList[11] = new favorite("TechWeb", "icmp",
Image from book "http://www.techWeb.ru/wire/wire.html");
FaveList[12] = new favorite("Netscape", "ntsc","http://devedge.netscape.ru/");
FaveList[13] = new favorite("Microsoft", "micr","http://msdn.microsoft.ru/");
// Search Engines Section -----------
FaveList[14] = new favorite("Search Engines", "", "");
FaveList[15] = new favorite("Yahoo!", "syah","http://www.yahoo.ru/");
FaveList[16] = new favorite("Alta Vista", "sav","http://www.altavista.ru/");
FaveList[17] = new favorite("Excite", "sexc","http://www.excite.ru/");
// Auction Section ------------------
FaveList[18] = new favorite("Auctions", "", "");
FaveList[19] = new favorite("ebay", "ebay","http://www.ebay.ru/");
FaveList[20] = new favorite("Yahoo Auctions", "yhac",
Image from book "http://auctions.yahoo.ru/");
// Misc. Section --------------------
FaveList[21] = new favorite("Misc.", "", "");
FaveList[22] = new favorite("Today in History", "mtih",
Image from book "http://www.thehistorynet.ru/today/today.htm");
FaveList[23] = new favorite("Merriam-Webster"s Word of the Day","mwod", 
Image from book "http://www.m-w.ru/cgi-bin/mwwod.pl");
FaveList[24] = new favorite("Quotes of the Day", "mquot",
Image from book "http://www.starlingtech.ru/quotes/qotd.html");
   
//===============================================================
// Page Writing Routines
//===============================================================
//---------------------------------------------------------------
// SendOptionsPage - Writes a page allowing the user to select
//                   her favorite preferences
//---------------------------------------------------------------
function SendOptionsPage()
{
  document.write("<h1>Select Favorites</h1>");
  document.write("<form method=post>");
  // Here"s the button for viewing the Favorites page
  document.write("<input type=button value="Show Favorites" "+ "onClick=""+
Image from book "ReloadPage()"+";">");
  // The links will look nicer inside a definition listdocument.write("<dl>");
  for (var i = 1; i < FaveList.length; i++)
    FaveList[i].WriteAsCheckBox();
  // Write each checkbox
  document.write("</dl><p>");
  ClearCookie("ViewAll");
  document.write("</form>");
}
   
//---------------------------------------------------------------
// LoadOptions - Sets the ShowOptions cookie, which makes the
//               option selection page appear when the page is
//               then reloaded.
//---------------------------------------------------------------
function LoadOptions()
{
  SetCookieEZ("ShowOptions", "T");
  window.open(document.location.href, "_top", "");
}
   
//---------------------------------------------------------------
// ToggleView - Toggles ViewAll mode on and off.  When on, all
//              links will be displayed.  When off, only the
//              user"s favorite selections will be displayed.
//---------------------------------------------------------------
function ToggleView()
{
  if (GetCookie("ViewAll") == "T")
  {
    ClearCookie("ViewAll");
  }
  else
  {
    var fiveYears = 5 * 365 * 24 * 60 * 60 * 1000;
    var expDate = new Date();
    expDate.setTime (expDate.getTime() + fiveYears );
    SetCookie("ViewAll", "T", expDate, null, null, false);
  }
  window.open(document.location.href, "_top", "");
}
   
//---------------------------------------------------------------
// SendPersonalPage - Writes a page showing the categories and
//                    links which the user prefers. Only shows a
//                    heading if one of its favorites is enabled
//---------------------------------------------------------------
function SendPersonalPage()
{
  if (GetCookie("ViewAll") != "T")
    document.write("<h1>Your Favorites:</h1>");
  else
    document.write("<h1>Links:</h1>");
  // Here are the buttons for viewing the options or
  // "View All" pages
  document.write("<form method=post>");
  if (GetCookie("ViewAll") == "T")
  {
    document.write("<input type=button value="View Favorites"
                   "+"onClick="ToggleView();">");
  }
  else
  {
    document.write("<input type=button value="View All" "+"onClick="ToggleView();">");
  }
  document.write("<input type=button "+ "value="Select Personal Favorites"
                    "+ "onClick="LoadOptions();">");
  document.write("</form>");
  // The links will look nicer inside a definition list
  document.write("<dl>");
  for (var i = 1; i < FaveList.length; i++)
    FaveList[i].WriteAsWebLink();    // Write each link
  document.write("</dl><p>");
}
   
//===============================================================
// Helper Functions
//===============================================================
//---------------------------------------------------------------
// isEnabled - Returns True if the favorite identified by the
//             name parameter is enabled.
//---------------------------------------------------------------
function isEnabled(name){
  var result = false;
  var FaveCookie = GetCookie("Favorites");
  if (FaveCookie != null)  {
    var searchFor = "<" + name + ">";
    var startOfCookie = FaveCookie.indexOf(searchFor);
    if (startOfCookie != -1)
      result = true;
  }
  return result;
}
   
//---------------------------------------------------------------
// AddFavorite- Enables the favorite identified by the name
//              parameter.
//---------------------------------------------------------------
function AddFavorite(name){
  if (!isEnabled(name))  {
    var fiveYears = 5 * 365 * 24 * 60 * 60 * 1000;
    var expDate = new Date();
    expDate.setTime (expDate.getTime() + fiveYears );
    SetCookie("Favorites", GetCookie("Favorites")+ "<" + name + 
                ">", expDate, null, null, false);
  }
}
   
//---------------------------------------------------------------
// ClearFavorite- Disables the favorite identified by the name
//                parameter.
//---------------------------------------------------------------
function ClearFavorite(name){
  if (isEnabled(name))  {
    var FaveCookie = GetCookie("Favorites");
    var searchFor = "<" + name + ">";
    var startOfCookie = FaveCookie.indexOf(searchFor);
    var NewFaves = FaveCookie.substring(0, startOfCookie)+ FaveCookie.substring(startOfCookie+searchFor.length,FaveCookie.length);
    var fiveYears = 5 * 365 * 24 * 60 * 60 * 1000;
    var expDate = new Date();
    expDate.setTime (expDate.getTime() + fiveYears );
    SetCookie("Favorites", NewFaves, expDate, null, null, false);
  }
}
   
//---------------------------------------------------------------
// SetFavoriteEnabled - Turns the favorite identified by the name
//                      parameter on (SetOn=true) or off
//                      (SetOn=false).
//---------------------------------------------------------------
function SetFavoriteEnabled(name, SetOn){
  if (SetOn)
    AddFavorite(name);
  else
    ClearFavorite(name);
}
   
//---------------------------------------------------------------
// ReloadPage - Reloads the page
//---------------------------------------------------------------
function ReloadPage(){
  window.open(document.location.href, "_top", "");
}
   
// End Commented Script -->
</script>
</head>
<body>
<script language="JavaScript">
<!-- Comment out script from browsers that don"t know JavaScript
/*---------------------------------------------------------------
Here"s where we select the page to send.  Normally we send the
personalized favorites page (by calling SendPersonalPage). However,
If the cookie ShowOptions is set, we"ll send the options selection
page instead (by calling SendOptionsPage).
---------------------------------------------------------------*/
if (GetCookie("ShowOptions") == "T"){
  ClearCookie("ShowOptions");
  SendOptionsPage();
}else{
  SendPersonalPage();
}
// End Commented Script -->
</script>
<center>This is a very dull page unless you have a JavaScriptenabled browser.<br></center>
</body>
</html>



A Cookie Test Program

  
<HTML>
<HEAD>
<TITLE>Cookie Test</TITLE>
<SCRIPT LANGUAGE="JavaScript"><!--
function updateCookie() {
 document.cookie=document.form1.cookie.value
 location.reload(true)
}
// --></SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
 document.write("Your current cookie value is: ""+ document.cookie+""")
</SCRIPT>
<FORM ACTION="" NAME="form1">
<P>Enter new cookie: <INPUT TYPE="TEXT" SIZE="60" NAME="cookie"></P>
<INPUT TYPE="BUTTON" NAME="setCookie" VALUE="Set Cookie" onClick="updateCookie()">
</FORM>
</BODY>
</HTML>



A Website Access Counter

  
/*
Mastering JavaScript, Premium Edition
by James Jaworski 
ISBN:078212819X
Publisher Sybex CopyRight 2001
*/
<HTML>
<HEAD>
<TITLE>Keeping track of Web site access</TITLE>
<SCRIPT LANGUAGE="JavaScript" ><!--
function nameDefined(c,n) {
 var s=removeBlanks(c)
 var pairs=s.split(";")
 for(var i=0;i<pairs.length;++i) {
  var pairSplit=pairs[i].split("=")
  if(pairSplit[0]==n) return true
 }
 return false
}
function removeBlanks(s) {
 var temp=""
 for(var i=0;i<s.length;++i) {
  var c=s.charAt(i)
  if(c!=" ") temp += c
 }
 return temp
}
function getCookieValue(c,n) {
 var s=removeBlanks(c)
 var pairs=s.split(";")
 for(var i=0;i<pairs.length;++i) {
  var pairSplit=pairs[i].split("=")
  if(pairSplit[0]==n) return pairSplit[1]
 }
 return ""
}
function insertSiteCounter() {
 readCookie()
 displayCounter()
}
function displayCounter() {
 document.write("<H3 ALIGN="CENTER">")
 document.write("Welcome! You"ve accessed this site ")
 if(counter==1) document.write("for the first time.")
 else document.write(counter+" times!")
 document.writeln("</H3>")
}
function readCookie() {
 var cookie=document.cookie
 counter=0
 if(nameDefined(cookie,"siteCount"))
  counter=parseInt(getCookieValue(cookie,"siteCount"))
 ++counter
 var newCookie="siteCount="+counter
 newCookie += "; expires=Wednesday, 10-Nov-10 23:12:40 GMT"
 newCookie += "; path=/"
 window.document.cookie=newCookie
}
// --></SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<SCRIPT LANGUAGE="JavaScript"><!--
insertSiteCounter()
// --></SCRIPT>
<H1 ALIGN="CENTER">Keeping track of Web site access</H1>
</body>
</HTML>



Bill Dortch"s Cookie Functions

  
/*
JavaScript Bible, Fourth Edition
by Danny Goodman 
Publisher: John Wiley & Sons CopyRight 2001
ISBN: 0764533428
*/

<html>
<head>
<title>Cookie Functions</title>
</head>
<body>
<script language="javascript">
<!-- begin script
//
//  Cookie Functions -- "Night of the Living Cookie" Version (25-Jul-96)
//
//  Written by:  Bill Dortch, hIdaho Design <bdortch@hidaho.ru>
//  The following functions are released to the public domain.
//
//  This version takes a more aggressive approach to deleting
//  cookies.  Previous versions set the expiration date to one
//  millisecond prior to the current time; however, this method
//  did not work in Netscape 2.02 (though it does in earlier and
//  later versions), resulting in "zombie" cookies that would not
//  die.  DeleteCookie now sets the expiration date to the earliest
//  usable date (one second into 1970), and sets the cookie"s value
//  to null for good measure.
//
//  Also, this version adds optional path and domain parameters to
//  the DeleteCookie function.  If you specify a path and/or domain
//  when creating (setting) a cookie**, you must specify the same
//  path/domain when deleting it, or deletion will not occur.
//
//  The FixCookieDate function must now be called explicitly to
//  correct for the 2.x Mac date bug.  This function should be
//  called *once* after a Date object is created and before it
//  is passed (as an expiration date) to SetCookie.  Because the
//  Mac date bug affects all dates, not just those passed to
//  SetCookie, you might want to make it a habit to call
//  FixCookieDate any time you create a new Date object:
//
//    var theDate = new Date();
//    FixCookieDate (theDate);
//
//  Calling FixCookieDate has no effect on platforms other than
//  the Mac, so there is no need to determine the user"s platform
//  prior to calling it.
//
//  This version also incorporates several minor coding improvements.
//
//  **Note that it is possible to set multiple cookies with the same
//  name but different (nested) paths.  For example:
//
//    SetCookie ("color","red",null,"/outer");
//    SetCookie ("color","blue",null,"/outer/inner");
//
//  However, GetCookie cannot distinguish between these and will return
//  the first cookie that matches a given name.  It is therefore
//  recommended that you *not* use the same name for cookies with
//  different paths.  (Bear in mind that there is *always* a path
//  associated with a cookie; if you don"t explicitly specify one,
//  the path of the setting document is used.)
//  
//  Revision History:
//
//    "Toss Your Cookies" Version (22-Mar-96)
//      - Added FixCookieDate() function to correct for Mac date bug
//
//    "Second Helping" Version (21-Jan-96)
//      - Added path, domain and secure parameters to SetCookie
//      - Replaced home-rolled encode/decode functions with Netscape"s
//        new (then) escape and unescape functions
//
//    "Free Cookies" Version (December 95)
//
//
//  For information on the significance of cookie parameters, 
//  and on cookies in general, please refer to the official cookie
//  spec, at:
//
//      http://www.netscape.ru/newsref/std/cookie_spec.html    
//
//******************************************************************
//
// "Internal" function to return the decoded value of a cookie
//
function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}
//
//  Function to correct for 2.x Mac date bug.  Call this function to
//  fix a date object prior to passing it to SetCookie.
//  IMPORTANT:  This function should only be called *once* for
//  any given date object!  See example at the end of this document.
//
function FixCookieDate (date) {
  var base = new Date(0);
  var skew = base.getTime(); // dawn of (Unix) time - should be 0
  if (skew > 0)  // Except on the Mac - ahead of its time
    date.setTime (date.getTime() - skew);
}
//
//  Function to return the value of the cookie specified by "name".
//    name - String object containing the cookie name.
//    returns - String object containing the cookie value, or null if
//      the cookie does not exist.
//
function GetCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
  }
return null;
}
//
//  Function to create or update a cookie.
//    name - String object containing the cookie name.
//    value - String object containing the cookie value.  May contain
//      any valid string characters.
//    [expires] - Date object containing the expiration data of the cookie.  If
//      omitted or null, expires the cookie at the end of the current session.
//    [path] - String object indicating the path for which the cookie is valid.
//      If omitted or null, uses the path of the calling document.
//    [domain] - String object indicating the domain for which the cookie is
//      valid. If omitted or null, uses the domain of the calling document.
//    [secure] - Boolean (true/false) value indicating whether cookie transmission
//      requires a secure channel (HTTPS).  
//
//  The first two parameters are required.  The others, if supplied, must
//  be passed in the order listed above.  To omit an unused optional field,
//  use null as a place holder.  For example, to call SetCookie using name,
//  value and path, you would code:
//
//      SetCookie ("myCookieName", "myCookieValue", null, "/");
//
//  Note that trailing omitted parameters do not require a placeholder.
//
//  To set a secure cookie for path "/myPath", that expires after the
//  current session, you might code:
//
//      SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
//
function SetCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=.uregina.ca" : "") +
    ((secure) ? "; secure" : "");
}
//  Function to delete a cookie. (Sets expiration date to start of epoch)
//   name -   String object containing the cookie name
//    path -   String object containing the path of the cookie to delete.  This MUST
//             be the same as the path used to create the cookie, or null/omitted if
//             no path was specified when creating the cookie.
//    domain - String object containing the domain of the cookie to delete.  This MUST
//             be the same as the domain used to create the cookie, or null/omitted if
//             no domain was specified when creating the cookie.
//
function DeleteCookie (name,path,domain) {
  if (GetCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=.uregina.ca" : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}
//
//  Examples
//
var expdate = new Date ();
FixCookieDate (expdate); // Correct for Mac date bug - call only once for given Date object!
expdate.setTime (expdate.getTime() + (24 * 60 * 60 * 1000)); // 24 hrs from now 
SetCookie ("ccpath", "http://www.hidaho.ru/colorcenter/", expdate);
SetCookie ("ccname", "hIdaho Design ColorCenter", expdate);
SetCookie ("tempvar", "This is a temporary cookie.");
SetCookie ("ubiquitous", "This cookie will work anywhere in this domain",null,"/");
SetCookie ("paranoid", "This cookie requires secure communications",expdate,"/",null,true);
SetCookie ("goner", "This cookie must die!");
document.write (document.cookie + "<br>");
DeleteCookie ("goner");
document.write (document.cookie + "<br>");
document.write ("ccpath = " + GetCookie("ccpath") + "<br>");
document.write ("ccname = " + GetCookie("ccname") + "<br>");
document.write ("tempvar = " + GetCookie("tempvar") + "<br>");
// end script -->
</script>
</body>
</html>



"cookieEnabled" Example

  
    
<html>
<body>
<button onClick="alert(navigator.cookieEnabled);">Are Cookies Enabled</button>
</body>
</html>



Cookie install and delete (remove)

  
/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition
Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan.  You may use, study, modify, and
distribute them for any purpose.  Please note that these examples are
provided "as-is" and come with no warranty of any kind.
David Flanagan
*/
<html>
<script language="JavaScript1.1">
// The constructor function: creates a cookie object for the specified
// document, with a specified name and optional attributes.
// Arguments:
//   document: The Document object that the cookie is stored for. Required.
//   name:     A string that specifies a name for the cookie. Required.
//   hours:    An optional number that specifies the number of hours from now
//             that the cookie should expire.
//   path:     An optional string that specifies the cookie path attribute.
//   domain:   An optional string that specifies the cookie domain attribute.
//   secure:   An optional Boolean value that, if true, requests a secure cookie.
//
function Cookie(document, name, hours, path, domain, secure)
{
    // All the predefined properties of this object begin with "$"
    // to distinguish them from other properties which are the values to
    // be stored in the cookie.
    this.$document = document;
    this.$name = name;
    if (hours)
        this.$expiration = new Date((new Date()).getTime() + hours*3600000);
    else this.$expiration = null;
    if (path) this.$path = path; else this.$path = null;
    if (domain) this.$domain = domain; else this.$domain = null;
    if (secure) this.$secure = true; else this.$secure = false;
}
// This function is the store() method of the Cookie object.
Cookie.prototype.store = function () {
    // First, loop through the properties of the Cookie object and
    // put together the value of the cookie. Since cookies use the
    // equals sign and semicolons as separators, we"ll use colons
    // and ampersands for the individual state variables we store 
    // within a single cookie value. Note that we escape the value
    // of each state variable, in case it contains punctuation or other
    // illegal characters.
    var cookieval = "";
    for(var prop in this) {
        // Ignore properties with names that begin with "$" and also methods.
        if ((prop.charAt(0) == "$") || ((typeof this[prop]) == "function")) 
            continue;
        if (cookieval != "") cookieval += "&";
        cookieval += prop + ":" + escape(this[prop]);
    }
    // Now that we have the value of the cookie, put together the 
    // complete cookie string, which includes the name and the various
    // attributes specified when the Cookie object was created.
    var cookie = this.$name + "=" + cookieval;
    if (this.$expiration)
        cookie += "; expires=" + this.$expiration.toGMTString();
    if (this.$path) cookie += "; path=" + this.$path;
    if (this.$domain) cookie += "; domain=" + this.$domain;
    if (this.$secure) cookie += "; secure";
    // Now store the cookie by setting the magic Document.cookie property.
    this.$document.cookie = cookie;
}
// This function is the load() method of the Cookie object.
Cookie.prototype.load = function() { 
    // First, get a list of all cookies that pertain to this document.
    // We do this by reading the magic Document.cookie property.
    var allcookies = this.$document.cookie;
    if (allcookies == "") return false;
    // Now extract just the named cookie from that list.
    var start = allcookies.indexOf(this.$name + "=");
    if (start == -1) return false;   // Cookie not defined for this page.
    start += this.$name.length + 1;  // Skip name and equals sign.
    var end = allcookies.indexOf(";", start);
    if (end == -1) end = allcookies.length;
    var cookieval = allcookies.substring(start, end);
    // Now that we"ve extracted the value of the named cookie, we"ve
    // got to break that value down into individual state variable 
    // names and values. The name/value pairs are separated from each
    // other by ampersands, and the individual names and values are
    // separated from each other by colons. We use the split method
    // to parse everything.
    var a = cookieval.split("&");    // Break it into array of name/value pairs.
    for(var i=0; i < a.length; i++)  // Break each pair into an array.
        a[i] = a[i].split(":");
    // Now that we"ve parsed the cookie value, set all the names and values
    // of the state variables in this Cookie object. Note that we unescape()
    // the property value, because we called escape() when we stored it.
    for(var i = 0; i < a.length; i++) {
        this[a[i][0]] = unescape(a[i][1]);
    }
    // We"re done, so return the success code.
    return true;
}
// This function is the remove() method of the Cookie object.
Cookie.prototype.remove = function() {
    var cookie;
    cookie = this.$name + "=";
    if (this.$path) cookie += "; path=" + this.$path;
    if (this.$domain) cookie += "; domain=" + this.$domain;
    cookie += "; expires=Fri, 02-Jan-1970 00:00:00 GMT";
    this.$document.cookie = cookie;
}

//===================================================================
//  The previous code is the definition of the Cookie class.
//  The following code is a sample use of that class.
//===================================================================
// Create the cookie we"ll use to save state for this web page.
// Since we"re using the default path, this cookie will be accessible
// to all web pages in the same directory as this file or "below" it.
// Therefore, it should have a name that is unique among those pages.
// Note that we set the expiration to 10 days in the future.
var visitordata = new Cookie(document, "name_color_count_state", 240);
// First, try to read data stored in the cookie. If the cookie is not
// defined, or if it doesn"t contain the data we need, then query the
// user for that data.
if (!visitordata.load() || !visitordata.name || !visitordata.color) {
    visitordata.name = prompt("What is your name:", "");
    visitordata.color = prompt("What is your favorite color:", "");
}
// Keep track of how many times this user has visited the page:
if (visitordata.visits == null) visitordata.visits = 0;
visitordata.visits++;
// Store the cookie values, even if they were already stored, so that the 
// expiration date will be reset to 10 days from this most recent visit.
// Also, store them again to save the updated visits state variable.
visitordata.store();
// Now we can use the state variables we read:
document.write("<font size="7" color="" + visitordata.color + "">" +
               "Welcome, " + visitordata.name + "!" +
               "</font>" +
               "<p>You have visited " + visitordata.visits + " times.");
</script>
<form>
<input type="button" value="Forget My Name" onclick="visitordata.remove();">
</form>
</html>



Cookie Preferences

  
/*
JavaScript Application Cookbook
By Jerry Bradenbaugh
Publisher: O"Reilly 
Series: Cookbooks
ISBN: 1-56592-577-7
*/


<A href="http://www.wbex.ru/Code/JavaScriptDownload/CookiePreferences.zip">CookiePreferences.zip( 183 k)</a>


Cookie: retrieve a future expiration date in proper format

  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- 
     Example File From "JavaScript and DHTML Cookbook"
     Published by O"Reilly & Associates
     Copyright 2003 Danny Goodman
-->
<html>
<head>
<title>Recipe 10.04a</title>
<style rel="stylesheet" id="mainStyle" type="text/css">
html {background-color:#cccccc}
body {background-color:#eeeeee; font-family:Tahoma,Arial,Helvetica,sans-serif; 
      font-size:12px;
    margin-left:15%; margin-right:15%; border:3px groove darkred; padding:15px}
h1 {text-align:right; font-size:1.5em; font-weight:bold}
h2 {text-align:left; font-size:1.1em; font-weight:bold; text-decoration:underline}
.buttons {margin-top:10px}
</style>
<script type="text/javascript">
/* cookies.js */
/*
     Example File From "JavaScript and DHTML Cookbook"
     Published by O"Reilly & Associates
     Copyright 2003 Danny Goodman
*/
// utility function to retrieve a future expiration date in proper format;
// pass three integer parameters for the number of days, hours,
// and minutes from now you want the cookie to expire; all three
// parameters required, so use zeros where appropriate
function getExpDate(days, hours, minutes) {
    var expDate = new Date();
    if (typeof days == "number" && typeof hours == "number" && typeof hours == "number") {
        expDate.setDate(expDate.getDate() + parseInt(days));
        expDate.setHours(expDate.getHours() + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
        return expDate.toGMTString();
    }
}
// utility function called by getCookie()
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}
// primary function to retrieve cookie by name
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
    }
    return null;
}
// store cookie value with optional details as needed
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
// remove the cookie by setting ancient expiration date
function deleteCookie(name,path,domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

</script>
<script language="JavaScript" type="text/javascript">
function saveValues() {
  setCookie("name1", document.forms[0].name1.value);
  setCookie("name2", document.forms[0].name2.value);
  setCookie("color", document.forms[0].color.options[document.forms[0].color.selectedIndex].value);
}
function applyValues() {
  var form = document.forms[0];
  form.name1.value = (getCookie("name1")) ? getCookie("name1") : "";
  form.name2.value = (getCookie("name2")) ? getCookie("name2") : "";
  var selValue = (getCookie("color")) ? getCookie("color") : "";
  if (selValue) {
    for (var i = 0; i < form.color.options.length; i++) {
      if (form.color.options[i].value == selValue) {
        form.color.selectedIndex = i;
        break;
      }
    }
  }
}
</script>
</head>
<body onunload="saveValues()" onload="applyValues()">
<form>
<h1>Page One</h1>
<hr>
First Name: <input type="text" name="name1" id="name1"><br>
Last Name: <input type="text" name="name2" id="name2"><br>
Your favorite color: <select id="color" name="color">
  <option value="">Pick a color:</option>
  <option value="Red">Red</option>
  <option value="Green">Green</option>
  <option value="Blue">Blue</option>
</select>
</form>
</body>
</html>



Cookie set, delete, get value and create

  
/*
JavaScript Application Cookbook
By Jerry Bradenbaugh
Publisher: O"Reilly 
Series: Cookbooks
ISBN: 1-56592-577-7
*/ 
 
<HTML>
<HEAD>
<TITLE>cookie set, delete, get value and create</TITLE>
<SCRIPT LANUAGE="JavaScript">
// cookies.js
// Derived from the Bill Dortch code at http://www.hidaho.ru/cookies/cookie.txt
var today = new Date();
var expiry = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000);
function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1) { endstr = document.cookie.length; }
  return unescape(document.cookie.substring(offset, endstr));
  }
function GetCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg) {
      return getCookieVal (j);
      }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
    }
  return null;
  }
function DeleteCookie (name,path,domain) {
  if (GetCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
  }
function SetCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
  }
</SCRIPT>
</HEAD>
<BODY BGCOLOR=WHITE>
<SCRIPT LANGUAGE="JavaScript">
<!--
if (GetCookie("user_id") == null) {
  var getName = prompt("Hi... First time, huh?? We all have to  through it. Please enter your name.", "");
  document.writeln("<H2>Welcome, " + (getName != "" ? getName : "Anonymous user") + "</H2>" + 
    "This is your first visit.");
  SetCookie("user_id", (getName != "" ? getName : "Anonymous user"), expiry);
  SetCookie("hit_count", "2", expiry);
  }
else {
  var getName = GetCookie("user_id");
  var getHits = GetCookie("hit_count");
  document.writeln("<H2>Welcome Back, " + getName + "</H2>" + 
    "You have visited " + getHits + " times.");
  getHits = parseInt(getHits) + 1;
  SetCookie("hit_count", "" + getHits + "", expiry);
  }
//-->
</SCRIPT>
</BODY>
</HTML>



Cookie utility function

  
/* cookies.js */
/*
     Example File From "JavaScript and DHTML Cookbook"
     Published by O"Reilly & Associates
     Copyright 2003 Danny Goodman
*/
// utility function to retrieve a future expiration date in proper format;
// pass three integer parameters for the number of days, hours,
// and minutes from now you want the cookie to expire; all three
// parameters required, so use zeros where appropriate
function getExpDate(days, hours, minutes) {
    var expDate = new Date();
    if (typeof days == "number" && typeof hours == "number" && typeof hours == "number") {
        expDate.setDate(expDate.getDate() + parseInt(days));
        expDate.setHours(expDate.getHours() + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
        return expDate.toGMTString();
    }
}
// utility function called by getCookie()
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}
// primary function to retrieve cookie by name
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
    }
    return null;
}
// store cookie value with optional details as needed
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
// remove the cookie by setting ancient expiration date
function deleteCookie(name,path,domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}



Create a cookie

  
    
<html>
<body>
<script language="JavaScript">
    myDate = new Date("12/22/2005 12:00 AM");
    document.cookie = "firstName=Joe; 
    expires=" + myDate.toString + ";";
</script>
<button onclick="alert(document.cookie);">See Document Cookie</button>
</body>
</html>



Keeping Track of User Access Time

  
/*
Mastering JavaScript, Premium Edition
by James Jaworski 
ISBN:078212819X
Publisher Sybex CopyRight 2001
*/
<HTML>
<HEAD>
<TITLE>Keeping track of Web site access time</TITLE>
<SCRIPT LANGUAGE="JavaScript"><!--
function nameDefined(c,n) {
 var s=removeBlanks(c)
 var pairs=s.split(";")
 for(var i=0;i<pairs.length;++i) {
  var pairSplit=pairs[i].split("=")
  if(pairSplit[0]==n) return true
 }
 return false
}
function removeBlanks(s) {
 var temp=""
 for(var i=0;i<s.length;++i) {
  var c=s.charAt(i)
  if(c!=" ") temp += c
 }
 return temp
}
function getCookieValue(c,n) {
 var s=removeBlanks(c)
 var pairs=s.split(";")
 for(var i=0;i<pairs.length;++i) {
  var pairSplit=pairs[i].split("=")
  if(pairSplit[0]==n) return pairSplit[1]
 }
 return ""
}
function insertTimeCounter() {
 today = new Date()
 startTime = today.getTime()
 readCookie()
 displayCounter()
 setInterval("setCookie()",1000)
}
function displayCounter() {
 document.write("<H3 ALIGN="CENTER">")
 document.write("Welcome! You"ve accessed this site ")
 if(prevTime==0) document.write("for the first time.")
 else document.write("over "+displayTime())
 document.writeln("</H3>")
}
function displayTime() {
 var seconds=Math.round(prevTime/1000)
 var minutes=Math.round(seconds/60)
 var hours=Math.round(minutes/60)
 if(seconds<60) return ""+seconds+ " seconds."
 else if(minutes<60) return ""+minutes+ " minutes."
 else return ""+hours+" hours "
}
function readCookie() {
 var cookie=document.cookie
 prevTime=0
 if(nameDefined(cookie,"timeCount"))
  prevTime=parseInt(getCookieValue(cookie,"timeCount"))
}
function setCookie() {
 now = new Date()
 endTime = now.getTime()
 duration = endTime-startTime
 var newCookie="timeCount="+(prevTime+duration)
 newCookie += "; expires=Wednesday, 10-Nov-10 23:12:40 GMT"
 newCookie += "; path=/"
 window.document.cookie=newCookie
}
// --></SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<SCRIPT LANGUAGE="JavaScript"><!--
insertTimeCounter()
// --></SCRIPT>
<H1 ALIGN="CENTER">Keeping track of Web site access time</H1>
<P ALIGN="CENTER">[The rest of the Web page goes here.]</P>
</BODY>



Quiz Program base on Cookie

  
/*
Mastering JavaScript, Premium Edition
by James Jaworski 
ISBN:078212819X
Publisher Sybex CopyRight 2001
*/
<HTML>
<HEAD>
<TITLE>Quiz Program</TITLE>
<SCRIPT LANGUAGE="JavaScript"><!--
//Question object
function Question() {
 this.question=Question.arguments[0]
 var n=Question.arguments.length
 this.answers = new Array(n-2)
 for(var i=1; i<n-1; ++i)
  this.answers[i-1]=Question.arguments[i]
 this.correctAnswer=Question.arguments[n-1]
}
function readCookie() {
 currentQuestion=0
 numberOfQuestions=0
 correctAnswers=0
 score="None"
 cookie=document.cookie
 currentQuestion=getNumberValue(cookie,"currentQuestion")
 numberOfQuestions=getNumberValue(cookie,"numberOfQuestions")
 correctAnswers=getNumberValue(cookie,"correctAnswers")
 if(numberOfQuestions>0)
  score=Math.round(correctAnswers*100/numberOfQuestions)
}
function getNumberValue(s,n) {
 s=removeBlanks(s)
 var pairs=s.split(";")
 for(var i=0;i<pairs.length;++i) {
  var pairSplit=pairs[i].split("=")
  if(pairSplit[0]==n) {
   if(pairSplit.length>1) return parseInt(pairSplit[1])
   else return 0
  }
 }
 return 0
}
function removeBlanks(s) {
 var temp=""
 for(var i=0;i<s.length;++i) {
  var c=s.charAt(i)
  if(c!=" ") temp += c
 }
 return temp
}
function askNextQuestion() {
 document.writeln("<H4 ALIGN="CENTER">"
  +qa[currentQuestion].question+"</H4>")
 displayAnswers()
}
function displayAnswers() {
 document.writeln("<FORM NAME="answerForm">")
 for(var ii=0;ii<qa[currentQuestion].answers.length;++ii) {
  document.writeln("<H4 ALIGN="CENTER">")
  document.writeln("<INPUT TYPE="RADIO" NAME="answer"> ")
  document.writeln(qa[currentQuestion].answers[ii])
  if(ii+1==qa[currentQuestion].answers.length) {
   document.writeln("<BR><BR><INPUT TYPE="BUTTON"")
   document.writeln("NAME="continue" VALUE="Continue" ")
   document.writeln(" onClick="checkAnswers()">")
  }
  document.writeln("</H4>")
 }
 document.writeln("</FORM>")
}
function checkAnswers() {
 var numAnswers=qa[currentQuestion].answers.length
 var correctAnswer=qa[currentQuestion].correctAnswer
 for(var jj=0;jj<numAnswers;++jj) {
  if(document.answerForm.elements[jj].checked) {
   if(jj==correctAnswer){
    correct()
     break
   }else{
     incorrect()
     break
   }
  }
  if(jj==numAnswers){
   incorrect()
   break
  }
 }
}
function correct() {
 ++currentQuestion
 ++numberOfQuestions
 ++correctAnswers
 updateCookie()
 location.reload(true)
}
function incorrect() {
 ++numberOfQuestions
 updateCookie()
 alert("Incorrect!")
 location.reload(true)
}
function updateCookie() {
 document.cookie="currentQuestion="+currentQuestion
 document.cookie="numberOfQuestions="+numberOfQuestions
 document.cookie="correctAnswers="+correctAnswers
}
function endQuiz() {
 document.cookie="currentQuestion=0"
 document.cookie="numberOfQuestions=0"
 document.cookie="correctAnswers=0"
 document.writeln("<FORM NAME="finishedForm">")
 document.write("<H4 ALIGN="CENTER">")
 document.write("Congratulations! You have finished this quiz.")
 document.write("<BR><BR><INPUT TYPE="BUTTON" ")
 document.writeln("NAME="restart" VALUE="Restart" ")
 document.writeln(" onClick="restartQuiz()">")
 document.writeln("</H4>")
 document.writeln("</FORM>")
}
function restartQuiz() {
 location.reload(true)
}
// --></SCRIPT>
<SCRIPT LANGUAGE="JavaScript"><!--
//Heading displayed on the quiz page
pageHeading="History Quiz"
//Questions
qa = new Array()
qa[0] = new Question("Who was the first president of the United States?",
 "George Washington",
 "Abraham Lincoln",
 "Benjamin Franklin",
 "Harry Truman",
 0)
qa[1] = new Question("When did Columbus discover America?",
 "1249",
 "1942",
 "1492",
 "1294",
 2)
qa[2] = new Question("Who commanded the Macedonian army?",
 "Napoleon",
 "Alexander the Great",
 "Cleopatra",
 "George Patton",
 1)
qa[3] = new Question("Where did Davy Crockett lose his life?",
 "The Spanish Inquisition",
 "The Alamo",
 "Miami, Florida",
 "On the Oregon Trail",
 1)
qa[4] = new Question("Who was the first man to walk on the moon?",
 "Louis Armstrong",
 "Buzz Armstrong",
 "Jack Armstrong",
 "Neil Armstrong",
 3)
qa[5] = new Question("Who wrote the <I>Scarlet Letter</I>?",
 "Michael Crichton",
 "Ernest Hemingway",
 "Nathaniel Hawthorne",
 "Charles Dickens",
 2)
qa[6] = new Question("Eli Whitney invented:",
 "Mad Cow"s Disease",
 "the Cotton Gin",
 "whisky",
 "the automobile",
 1)
qa[7] = new Question("Who was known as the King of the Fauves?",
 "Salvatore Dali",
 "Henri Matisse",
 "Pablo Picasso",
 "Vincent Van Gogh",
 1)
qa[8] = new Question("Who discovered the force of gravity?",
 "Isaac Newton",
 "Galileo",
 "Copernicus",
 "Albert Einstein"
 ,0)
qa[9] = new Question("Who created HTML?",
 "Tim Berners-Lee",
 "Marc Andreessen",
 "Bill Gates",
 "Jim Barksdale",
 0)
qa[10] = new Question("Leonardo da Vinci was born in Greece.",
 "True",
 "False",
 1)
qa[11] = new Question("Louisiana was purchased from France.",
 "True",
 "False",
 0)
// --></SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript"><!--
readCookie()
document.writeln("<H1 ALIGN="CENTER">"+pageHeading+"</H1>")
document.writeln("<P ALIGN="RIGHT"><B>Questions: "
 +numberOfQuestions+"<BR>")
document.writeln("Correct Answers: "+correctAnswers+"<BR>")
document.writeln("Score: "+score+"</B></P>")
if(currentQuestion >= qa.length) endQuiz()
else askNextQuestion()
// --></SCRIPT>
</BODY>
</HTML>



Read all cookies

 

<html>
<head>
<title>Reading Cookie</title>
<script type = "text/javascript">
var incCookies = document.cookie.split(";");
for (var c = 0; c < incCookies.length; c++) {
    var splitCookies = incCookies[c].split("=");
    if (splitCookies[0] == "cookie1") {
        alert(incCookies[c]);
    }
}
</script>
</head>
<body>
<p>Hello</p>
</body>
</html>



Reads, writes and deletes current Web page"s cookies

  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
  <HEAD>
    <TITLE>JsLib 1.3 - Exemple - cookies.js</TITLE>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
    <META NAME="Author" CONTENT="Etienne CHEVILLARD">
    <SCRIPT TYPE="text/javascript" LANGUAGE="Javascript">
/* cookies.js
 * Role : lit, ecrit et efface les cookies de la page Web courante
 * Projet : JsLib
 * Auteur : Etienne CHEVILLARD (echevillard@users.sourceforge.net)
 * Version : 1.3
 * Creation : 11/04/2001
 * Mise a jour : 23/02/2005
 */
// --- Variables globales ---
// vrai si le navigateur accepte les cookies
var cookies_ok=false;
// --- Fonctions ---
// indique si le navigateur accepte les cookies
function accepteCookies() {
  cookies_ok=false;
  if (navigator.cookieEnabled) {
    cookies_ok=true;
  } else {
    ecrireCookie ("jslib_cookie", "ok");
    if (lireCookie("jslib_cookie")=="ok") { cookies_ok=true; }
    effacerCookie("jslib_cookie");
  }
  return (cookies_ok);
} // fin accepteCookies()
// ecrit un cookie de nom et valeur specifiees pour le nombre de jours specifie
function ecrireCookie(nom, valeur, jours) {
  if (!nom || nom=="") return false;
  if (!valeur) { valeur=""; }
  if (!jours) { jours=0; }
  var expire;
  if (parseInt(jours)!=0) {
    var date=new Date();
    date.setTime(date.getTime()+(parseInt(jours)*24*60*60*1000));
    expire="; expires="+date.toGMTString();
  } else {
    expire="";
  }
  document.cookie=nom+"="+escape(valeur)+expire+"; path=/";
  return true;
} // fin ecrireCookie(nom, valeur, jours)
// efface le cookie de nom specifie
function effacerCookie(nom) {
  return (ecrireCookie(nom, "", -1));
} // fin effacerCookie(nom)
// lit et retourne la valeur du cookie de nom specifie
function lireCookie(nom) {
  if (!nom || nom=="") return ("");
  var nomEq=nom+"=";
  var tab=document.cookie.split(";");
  for(var i=0; i<tab.length; i++) {
    var cook=tab[i];
    while (cook.charAt(0)==" ")
      cook=cook.substring(1, cook.length);
    if (cook.indexOf(nomEq)==0)
      return unescape(cook.substring(nomEq.length, cook.length));
  }
  return ("");
} // fin lireCookie(nom)
    </SCRIPT>
  </HEAD>
  <BODY>
    <H1>JsLib 1.3</H1>
    <HR>
    <H2>Exemple - cookies.js</H2>
    <NOSCRIPT>
      <P><I>Erreur : votre navigateur ne reconnait pas le Javascript ou est configur&eacute; pour ne
      pas prendre en compte le code Javascript. Dans ce dernier cas, vous pouvez modifier la
      configuration dans les pr&eacute;f&eacute;rences/options de votre navigateur.</I>
      <HR>
    </NOSCRIPT>
    <P>Votre navigateur accepte-il les cookies ?
      <SCRIPT TYPE="text/javascript" LANGUAGE="Javascript">
        if (accepteCookies()) document.write("oui");
        else document.write("non");
      </SCRIPT>
    <P>Votre pr&eacute;nom est :
      <SCRIPT TYPE="text/javascript" LANGUAGE="Javascript">
        if (accepteCookies()) {
          if (lireCookie("prenom").length < 1) {
            var reponse;
            while (!reponse) reponse = window.prompt("Veuillez saisir votre nom ou pseudonyme :", "Toto");
            ecrireCookie("prenom", reponse, 3650);
          }
          document.write(lireCookie("prenom"));
        }
      </SCRIPT>
        <FORM ACTION="GET" NAME="f1">
          <INPUT TYPE=BUTTON VALUE="Modifier mon pr&eacute;nom"
          onClick="effacerCookie("prenom"); window.location.reload(true);">
        </FORM>
    <P>Nombre de visites effectu&eacute;es sur cette page :
      <SCRIPT TYPE="text/javascript" LANGUAGE="Javascript">
        if (accepteCookies()) {
          if (lireCookie("visites").length < 1) {
            ecrireCookie("visites", "0", 3650);
          }
          ecrireCookie("visites", parseInt(lireCookie("visites"))+1, 3650);
          document.write(lireCookie("visites"));
        }
      </SCRIPT>
  </BODY>
</HTML>


<A href="http://www.wbex.ru/Code/JavaScriptDownload/JsLib13.zip">JsLib13.zip( 311 k)</a>


Save name to cookie

  
<HTML>
<HEAD>
<SCRIPT language="JavaScript">
<!--
function set_it()
{
 var thename= window.prompt("What is your name?","");
 var the_text="name="+thename+"&";
 var toexpire= new Date("March 01, 2008");
 var expdate="expires="+toexpire.toGMTString();
 the_text+=expdate;
 
 var newtext=escape(the_text);
 document.cookie=newtext;
}
function read_it()
{
 if (document.cookie)
 {
  var mycookie=document.cookie;
  var fixed_cookie= unescape(mycookie);
  var thepairs= fixed_cookie.split("&");
  var pair1= thepairs[0];
  var pair2= thepairs[1];
  var namevalue1= pair1.split("=");
  window.alert("Welcome, "+namevalue1+"!");
 } else {
   set_it();
 }
}
read_it();
//-->
</SCRIPT>
</HEAD>
<BODY>
text text text
</BODY>
</HTML>



Secure cookie

 
<html>
<head>
<title>Hello Cookie</title>
<script type = "text/javascript">
var cookName = "cookie2";
var cookVal = "testvalue";
var date = new Date();
date.setTime(date.getTime()+86400000);
var expireDate = date.toGMTString();
var myCookie = cookName + "=" + cookVal + ";expires=" + expireDate + ";secure";
document.cookie = myCookie;
</script>
</head>
<body>
<p>Hello</p>
</body>
</html>



Set cookie to document and read it back

  
<HTML>
<HEAD>
<SCRIPT language="JavaScript">
function setCookie(){
  var thename= "your name";
  var the_text="name="+thename+"&";
  var toexpire= new Date("March 31, 2010");
  var expdate="expires="+toexpire.toGMTString();
  the_text+=expdate;
 
  var newtext=escape(the_text);
  document.cookie=newtext;

  var mycookie=document.cookie;
  var fixed_cookie= unescape(mycookie);
  var thepairs= fixed_cookie.split("&");
  var pair1= thepairs[0];
  var pair2= thepairs[1];
  var namevalue= pair1.split("=");
  window.alert("Welcome, "+namevalue[1]+"!");
 
}
setCookie();
</SCRIPT>
</HEAD>
<BODY>
text
</BODY>
</HTML>



Set the cookie expire date

 
<html>
<head>
<title>Hello Cookie</title>
<script type = "text/javascript">
var cookName = "cookie1";
var cookVal = "testvalue";
var date = new Date();
date.setTime(date.getTime()+86400000);
var expireDate = date.toGMTString();
var myCookie = cookName + "=" + cookVal + ";expires=" + expireDate;
document.cookie = myCookie;
</script>
</head>
<body>
<p>Hello</p>
</body>
</html>



Standard cookie functions: extract Cookie Value

  
<html>
<script language="JavaScript">
<!--
var visits = 0;
function extractCookieValue(val) {
  if ((endOfCookie = document.cookie.indexOf(";", val)) == -1) {
     endOfCookie = document.cookie.length;
  }
  return unescape(document.cookie.substring(val,endOfCookie));
}
function ReadCookie(cookiename) {
  var numOfCookies = document.cookie.length;
  var nameOfCookie = cookiename + "=";
  var cookieLen = nameOfCookie.length;
  var x = 0;
  while (x <= numOfCookies) {
        var y = (x + cookieLen);
        if (document.cookie.substring(x, y) == nameOfCookie)
           return (extractCookieValue(y));
           x = document.cookie.indexOf(" ", x) + 1;
           if (x == 0){
              break;
           }
  }
  return (null);
}
function createCookie(name, value, expiredays) {
  var todayDate = new Date();
  todayDate.setDate(todayDate.getDate() + expiredays);
  document.cookie = name + "=" + value + "; expires=" +todayDate.toGMTString() + ";"
}
function showHits() {
  userCookie = ReadCookie("_visitSite");
  if (userCookie == null)
     visits = 1;
  else
     visits = parseInt(userCookie) + 1;
     createCookie("_visitSite", visits, 30);
     document.write("You have visited this site on <b>" +visits + "</b> occasions<hr>");
}
//-->
</script>
</head>
<body>
<script>
showHits();
</script>
</body>
</html>