document.cookie

In this chapter you will learn:

  1. How to read and write cookies with Javascript
  2. How to use additional fields

Reads and writes cookies

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

<!DOCTYPE HTML> <!--from  ja  va2s .  com-->
<html> 
<body> 
<script> 
  var cookieCount = 0; 
  //read Cookies
  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";

Next chapter...

What you will learn in the next chapter:

  1. How to get document default character set
Home » Javascript Tutorial » Document
Document Object
document.body
document.characterSet
document.charset
document.compatMode
document.cookie
document.defaultCharset
document.defaultView
getElementsByTagName(tagName)
document.getElementsByClassName
document.getElementsByName
document.images
document.lastModified
document.location
document.implementation
document.querySelectorAll
document.readyState
document.title
document.URL
document.writeln