spacer.png, 0 kB
spacer.png, 0 kB
Home arrow Javascript arrow Cookies and Javascript
Cookies and Javascript PDF Print E-mail
A cookie is a small quantity of data stored by the browser and linked to a specific Web page.Is a kind of memory allowing the different pages to share information or just save user preferences or choices. 

Cookies were initially created as a CGI implementation: transmitted between browser and server were used to store client data.
Javascript allows cookie management thanks to the document object (document.cookie).

In order to store a cookie with Javascript you can just assign cookie property to a string as per this nome=valore schema below
document.cookie = "version" + escape(document.lastModified);
When the cookie is read the name/value data will be stored and included in the document cookie list.
The escape() Javascript function decodes the string in input that should have no full stops, commas, colons, semicolons or blank spaces.

However a cookie created with the above example is valid just for the current browser session. For a better control an expiry date should be provided setting the expires attribute (name=value; expires=data).
Date value is in milliseconds: 3 seconds = 3 * 1,000 (2 minutes  =  2  * 60 * 1,000).
The date should be in the Date.toGMTString() format.
var year = new Date();
year.setFullYear(year.getFullYear() + 1);
document.cookie = "version=" + document.lastModified +
                  "; expires=" + year.toGMTString();
With the same rule you can add also the path, domain, secure attributes
; path=mypath
; domain=mydomain
; secure
To modify a cookie you can just reassign another value to the same name.
To remove a cookie you can just set a past date (even if the cookie could remain in the browser list marked as outdated).
Don't forget finally that cookies were ideated to store small data quantities. We strongly suggest then gather more variables into the same cookie (considered the limited number provided) and not store long strings. 
Use the below list as the browser minimum requirements:
  • 4KB (4096 bytes) a cookie
  • 20 cookies a domain
  • 300 cookies maximum
Last Updated ( giovedě, 29 novembre 2007 )
< Prev   Next >
spacer.png, 0 kB
spacer.png, 0 kB
spacer.png, 0 kB