YUI recommends YUI3.

YUI 2 has been deprecated since 2011. This site acts as an archive for files and documentation.

This documentation is no longer maintained.

YUI 2: Cookie Utility

YUI 2: Cookie Utility

The YUI Cookie utility provides a simple API for interacting with cookies, including the creation and manipulation of subcookies.

Note about HTTPOnly Cookies: HTTPOnly cookies are cookies that may be set either by JavaScript or by the server but cannot be read from JavaScript. The YUI Cookie utility does not provide support for setting HTTPOnly cookies because browser support is not well-established and there is no fallback mechanism. Setting an HTTPOnly cookie on a browser that doesn't support it is the same as setting any other cookie (no error is thrown). When all A-grade browsers support HTTPOnly cookies, we will revisit adding support for it in the Cookie utility.

Getting Started

To use the Cookie utility, include the following source files in your web page:

  1. <!-- Dependencies -->
  2. <script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
  3.  
  4. <!-- Source File -->
  5. <script src="http://yui.yahooapis.com/2.9.0/build/cookie/cookie-min.js"></script>
  6.  
<!-- Dependencies -->
<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
 
<!-- Source File -->
<script src="http://yui.yahooapis.com/2.9.0/build/cookie/cookie-min.js"></script>
 

YUI dependency configurator.

YUI Dependency Configurator:

Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components; the Configurator uses YUI Loader to write out the full HTML for including the precise files you need for your implementation.

Note: If you wish to include this component via the YUI Loader, its module name is cookie. (Click here for the full list of module names for YUI Loader.)

Where these files come from: The files included using the text above will be served from Yahoo! servers. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the -debug versions of YUI JavaScript files, please download the library distribution and host the files on your own server.

Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.

Creating Cookies

The simplest way to create a cookie is to provide a name and a value to the set() method:

  1. YAHOO.util.Cookie.set("name", "value");
  2.  
YAHOO.util.Cookie.set("name", "value");
 

This example creates a cookie called "name" that has a value of "value". Since this cookie is created with all of the default settings, it becomes a session cookie.

There is a third argument for set(), which is an object containing additional settings for the cookie. To create a persistent cookie, you can specify an expiration date by supplying a Date object:

  1. YAHOO.util.Cookie.set("name", "value", {
  2. expires: new Date("January 12, 2025")
  3. });
  4.  
YAHOO.util.Cookie.set("name", "value", {
    expires: new Date("January 12, 2025")
});
 

By providing an "expires" option in the third argument, the cookie persists until the given date. In this example, the cookie will remain until January 12, 2025. The value for "expires" must be a Date object, otherwise it is ignored.

It's possible to restrict access to a cookie by setting path and/or domain information. Setting a path on the cookie restricts access to pages that match that path; setting a domain restricts access to pages on a given domain (typically used to allow cookie access across subdomains). Both options can be easily set using the "path" and "domain" options:

  1. YAHOO.util.Cookie.set("name", "value", {
  2. path: "/", //all pages
  3. domain: "yahoo.com" //any subdomain of yahoo.com, including www.yahoo.com
  4. });
  5.  
YAHOO.util.Cookie.set("name", "value", {
    path: "/",           //all pages
    domain: "yahoo.com"   //any subdomain of yahoo.com, including www.yahoo.com
});
 

In this example, a cookie is created that can be accessed from all pages on a yahoo.com subdomain. This cookie would then be accessible from pages on sports.yahoo.com as well as www.yahoo.com. The "path" and "domain" options need not be used together; they may be used independently as well.

The last option is "secure", which indicates that the cookie should only be accessible via SSL on a page using the HTTPS protocol. All other aspects of the cookie remain the same based on the other options provided. To set a secure cookie, use the "secure" option:

  1. YAHOO.util.Cookie.set("name", "value", {
  2. secure: true
  3. });
  4.  
YAHOO.util.Cookie.set("name", "value", {
    secure: true
});
 

This code creates a secure cookie by setting the "secure" option to true. Note that this will only work if the page calling this code uses the HTTPS protocol, otherwise the cookie will be created with default options.

Reading Cookies

The get() method retrieves cookies that are accessible by the current page. If a cookie doesn't exist, get() returns null.

  1. var value = YAHOO.util.Cookie.get("name");
  2.  
var value = YAHOO.util.Cookie.get("name");
 

This example retrieves the cookie called "name" and stores its value in the variable value. By default, values returned by get() are strings (if the cookie exists) or null (if the cookie doesn't exist). You can change the return value by providing a conversion function as the second argument. For example, to return a number, you can pass in the native Number() function:

  1. var value = YAHOO.util.Cookie.get("age", Number);
  2.  
var value = YAHOO.util.Cookie.get("age", Number);
 

In this code, the returned cookie value will be a number if the cookie exists (it will still be null if the cookie doesn't exist). Other native functions that convert values are Boolean() and Date, or you can define your own conversion function:

  1. var value = YAHOO.util.Cookie.get("code", function(stringValue) {
  2. //create a number from a hexadecimal code
  3. return parseInt(stringValue, 16);
  4. });
  5.  
var value = YAHOO.util.Cookie.get("code", function(stringValue) {
    //create a number from a hexadecimal code
    return parseInt(stringValue, 16);
});
 

Conversion functions accept a single argument, the string value of the cookie, and must return a value. In this example, the conversion function expects a hexadecimal code to be returned and passes it into parseInt() to convert the value into a number. Note that the conversion function is never called if the cookie doesn't exist (get() always returns null when the cookie doesn't exist).

Deleting Cookies

When a cookie is no longer need, it can be removed from the browser by calling the remove() method. This method takes two arguments: the name of the cookie to remove and an optional cookie options object. A cookie created with specific options can only be deleted by specifying the same options. For instance, a cookie created with a domain property of "yahoo.com" can only be deleted by also specifying the domain property as "yahoo.com". Examples:

  1. //delete the cookie named "code"
  2. YAHOO.util.Cookie.remove("code");
  3.  
  4. //delete the cookie named "info" on the "yahoo.com" domain
  5. YAHOO.util.Cookie.remove("info", {
  6. domain: "yahoo.com"
  7. });
  8.  
  9. //delete a secure cookie named "username"
  10. YAHOO.util.Cookie.remove("username", {
  11. secure: true
  12. });
  13.  
//delete the cookie named "code"
YAHOO.util.Cookie.remove("code");
 
//delete the cookie named "info" on the "yahoo.com" domain
YAHOO.util.Cookie.remove("info", {
    domain: "yahoo.com"
});
 
//delete a secure cookie named "username"
YAHOO.util.Cookie.remove("username", {
    secure: true
});
 

Subcookies

Each browser has a limit to the number of cookies that can be set per domain. These limits can be problematic for domains with different sites under different subdomains. Since cookie name-value pairs are rarely large enough to reach the byte limit for an individual cookie, it represents an opportunity to store multiple name-value pairs in a single cookie; these are called subcookies.

A subcookie string looks similar to a URL and takes the following form:

cookiename=name1=value1&name2=value2&name3=value3

The Cookie utility supports this style of subcookies to allow multiple values to be stored in a single cookie. To set a subcookie value, use the setSub() method. This method accepts four arguments: the cookie name, the subcookie name, the subcookie value, and an optional options object. Note that the options object works on the entire cookie, it is not specific to the subcookie.

  1. //set a cookie named "name" with a subcookie named "subname" whose value is "value"
  2. YAHOO.util.Cookie.setSub("name", "subname", "value");
  3.  
  4. //set a second subcookie on "name", with a name of "subname2" and a value of "value2"
  5. YAHOO.util.Cookie.setSub("name", "subname2", "value2");
  6.  
  7. //set subcookie on the "yahoo.com" domain
  8. YAHOO.util.Cookie.setSub("info", "age", 22, {
  9. domain: "yahoo.com"
  10. });
  11.  
  12. //set subcookie to a secure cookie named "user"
  13. YAHOO.util.Cookie.setSub("user", "name", "ace123", {
  14. secure:true
  15. });
  16.  
//set a cookie named "name" with a subcookie named "subname" whose value is "value"
YAHOO.util.Cookie.setSub("name", "subname", "value");
 
//set a second subcookie on "name", with a name of "subname2" and a value of "value2"
YAHOO.util.Cookie.setSub("name", "subname2", "value2");
 
//set subcookie on the "yahoo.com" domain
YAHOO.util.Cookie.setSub("info", "age", 22, {
    domain: "yahoo.com"
});
 
//set subcookie to a secure cookie named "user"
YAHOO.util.Cookie.setSub("user", "name", "ace123", {
    secure:true
});
 

It's possible to set the entire contents of a subcookie by using the setSubs() method, which accepts three arguments: the name of the cookie, and object containing name-value pairs, and an optional cookie options object. For instance, this code sets three subcookies at once:

  1. var oData = {
  2. name: "ace123",
  3. age: 22,
  4. track: true
  5. };
  6.  
  7. //set a cookie named "user" with subcookies
  8. YAHOO.util.Cookie.setSubs("user", oData);
  9.  
var oData = {
    name: "ace123",
    age: 22,
    track: true
};
 
//set a cookie named "user" with subcookies
YAHOO.util.Cookie.setSubs("user", oData);
 

Note that calls to setSubs() will always completely overwrite the cookie.

To retrieve subcookie values, there are two methods. The first is getSub(), which retrieves a single subcookie value. This method accepts three arguments: the cookie name, the subcookie name, and an optional converter function. As with get(), the converter function changes the data or type of data retrieved from the cookie before it's returned (and isn't called at all if the cookie or subcookie doesn't exist):

  1. //get subcookie
  2. var sValue = YAHOO.util.Cookie.getSub("name", "subname");
  3.  
  4. //get subcookie and convert to number
  5. var nValue = YAHOO.util.Cookie.getSub("user", "age", Number);
  6.  
  7. //get subcookie and convert from hex code to decimal number
  8. var iValue = YAHOO.util.Cookie.getSub("settings", "bgcolor", function (stringValue) {
  9. //create a number from a hexadecimal code
  10. return parseInt(stringValue, 16);
  11. });
  12.  
//get subcookie
var sValue = YAHOO.util.Cookie.getSub("name", "subname");
 
//get subcookie and convert to number
var nValue = YAHOO.util.Cookie.getSub("user", "age", Number);
 
//get subcookie and convert from hex code to decimal number
var iValue = YAHOO.util.Cookie.getSub("settings", "bgcolor", function (stringValue) {
    //create a number from a hexadecimal code
    return parseInt(stringValue, 16);
});
 

The second method to retrieve subcookies is getSubs(), which retrieves all subcookies and returns an object with name-value pairs for each subcookie. The getSubs() method takes a single argument, the name of the cookie containing subcookies to retrieve. The returned value is either an object or null if the cookie doesn't exist.

  1. //get all subcookies
  2. var oData = YAHOO.util.Cookie.getSubs("name");
  3. var sSubValue = oData.subname;
  4.  
  5. //get all subcookies
  6. var oUser = YAHOO.util.Cookie.getSubs("user");
  7. var sUserName = oUser.name;
  8.  
//get all subcookies
var oData = YAHOO.util.Cookie.getSubs("name");
var sSubValue = oData.subname;
 
//get all subcookies
var oUser = YAHOO.util.Cookie.getSubs("user");
var sUserName = oUser.name;
 

Removing subcookies is accomplished using the removeSub() method. This method accepts three arguments: the cookie name, the subcookie name, and an optional cookie options object. The options object, if specified, must have the same options as when the cookie was originally created. Example:

  1. //set subcookie on the "yahoo.com" domain
  2. YAHOO.util.Cookie.setSub("info", "age", 22, {
  3. domain: "yahoo.com"
  4. });
  5.  
  6. //remove the subcookie
  7. YAHOO.util.Cookie.removeSub("info", "age", {
  8. domain: "yahoo.com"
  9. });
  10.  
//set subcookie on the "yahoo.com" domain
YAHOO.util.Cookie.setSub("info", "age", 22, {
    domain: "yahoo.com"
});
 
//remove the subcookie
YAHOO.util.Cookie.removeSub("info", "age", {
    domain: "yahoo.com"
});
 

Removing a subcookie keeps all other subcookies for that cookie intact. If you want to remove all subcookies, it's easiest to use remove() to remove the entire cookie.

YUI on Mobile: Using Cookie with "A-Grade" Mobile Browsers

About this Section: YUI generally works well with mobile browsers that are based on A-Grade browser foundations. For example, Nokia's N-series phones, including the N95, use a browser based on Webkit — the same foundation shared by Apple's Safari browser, which is found on the iPhone. The fundamental challenges in developing for this emerging class of full, A-Grade-derived browsers on handheld devices are:

  • Screen size: You have a much smaller canvas;
  • Input devices: Mobile devices generally do not have mouse input, and therefore are missing some or all mouse events (like mouseover);
  • Processor power: Mobile devices have slower processors that can more easily be saturated by JavaScript and DOM interactions — and processor usage affects things like battery life in ways that don't have analogues in desktop browsers;
  • Latency: Most mobile devices have a much higher latency on the network than do terrestrially networked PCs; this can make pages with many script, css or other types of external files load much more slowly.

There are other considerations, many of them device/browser specific (for example, current versions of the iPhone's Safari browser do not support Flash). The goal of these sections on YUI User's Guides is to provide you some preliminary insights about how specific components perform on this emerging class of mobile devices. Although we have not done exhaustive testing, and although these browsers are revving quickly and present a moving target, our goal is to provide some early, provisional advice to help you get started as you contemplate how your YUI-based application will render in the mobile world.

More Information:

The Cookie utility works without any major issues on the Nokia N95 and Apple iPhone default browsers and we'd expect similar behavior on other A-Grade-based mobile browsers.

Support & Community

The YUI Library and related topics are discussed on the on the YUILibrary.com forums.

Also be sure to check out YUIBlog for updates and articles about the YUI Library written by the library's developers.

Filing Bugs & Feature Requests

The YUI Library's public bug tracking and feature request repositories are located on the YUILibrary.com site. Before filing new feature requests or bug reports, please review our reporting guidelines.

Cookie Utility Cheat Sheet:

Cheat Sheet for the YUI Cookie utility

Download full set of cheat sheets.

The YUI Cookie Utility on del.icio.us:

bookmark on del.icio.us

be the first to bookmark this page!

Copyright © 2013 Yahoo! Inc. All rights reserved.

Privacy Policy - Copyright Policy - Job Openings