How to read and write cookies with Javascript

Reads and writes cookies

document.cookie property allows you to read, add to, and update the cookies associated with the document.

Example


<!DOCTYPE HTML> 
<html> 
<body> 
<script> 
  var cookieCount = 0; 
  //read Cookies<!--from ww  w  . ja  va  2s .c o  m-->
  document.writeln(document.cookie); 
  //create Cookie
  cookieCount++; 
  document.cookie = "Cookie_" + cookieCount + "=Value_" + cookieCount; 
  //read Cookies
  document.writeln(document.cookie); 

  //update Cookie
  document.cookie = "Cookie_" + cookieCount + "=Updated_" + cookieCount; 
  //read Cookies
  document.writeln(document.cookie); 
</script> 
</body> 
</html>

Click to view the demo

The additional fields that can be added to a cookie

AdditionDescription
path=<path>cookie path; default to the path of the current document if not specified.
domain=<domain> cookie domain; defaults to the domain of the current document if not specified.
max-age=<seconds>the life of the cookie in terms of the number of seconds.
expires=<date>Sets the life of the cookie using a GMT-format date.
secureThe cookie will be sent only over a secure (HTTPS) connection.

Each of these additional items is prepended to the name/value pair and separated with a semicolon:


document.cookie = "MyCookie=MyValue;max-age=10";




















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window