Browsers have a limit on number of cookies that can be stored per domain. This limit is overcome by using what is called subcookies. In subcookies multiple cookies are stored within a single cookie. Subcookies are written in this format:

Syntax for subcookies

cookieName=name1=value1&&name2=value2&&name3=value3;

Where: name1=value1 is an individual cookie and && is their separator.

While writing subcookies, the value of the separator has to be chosen carefully as a subcookie's name or value should exclude some characters (for example: character like ‘/’ is bad idea as if a cookie stores URL like ‘http://webpage.html’ it might be decoded as a subcookie), or else it may produce wrong values.

NOTE: Although domain limit can be solved by subcookies, it should not be overdone. The domains or servers are allowed to store only only 4KB of data, i.e. 4096 characters.

In the min example below, the subcookies called “books” are created and stored in a cookie called “Library”. With addsubCookie() function the cookieName is created and values are stored in this format:

Library = subCookie0:learnComputer&&subCookie1:learning&&subCookie2:learnJavascript&&subCookie3:learnDriving

The displayCookies() function calls getSubCookie() to get the ‘Library’ cookie from the list of cookies stored for this domain. From the ‘Library’ cookie the subcookies are split at subcookie separator ‘&&’. The name and value of each subcookie is displayed. 

When a subcookie is deleted, the parent cookie has to be reconstructed with the remaining subcookies. The delCookie() deletes the subcookie1 from cookie list and creates a new cookie called newBooks to which, rest of the subcookies values are restored.

Example of subcookies in JavaScript

 

›› go to examples ››