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.
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.
To use the Cookie utility, include the following source files in your web page:
<!-- 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>
<!-- 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>
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.
The simplest way to create a cookie is to provide a name and a value to the set()
method:
YAHOO.util.Cookie.set("name", "value");
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:
YAHOO.util.Cookie.set("name", "value", { expires: new Date("January 12, 2025") });
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:
YAHOO.util.Cookie.set("name", "value", { path: "/", //all pages domain: "yahoo.com" //any subdomain of yahoo.com, including www.yahoo.com });
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:
YAHOO.util.Cookie.set("name", "value", { secure: true });
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.
The get()
method retrieves cookies that are accessible by the current page. If a cookie doesn't exist,
get()
returns null
.
var value = YAHOO.util.Cookie.get("name");
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:
var value = YAHOO.util.Cookie.get("age", Number);
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:
var value = YAHOO.util.Cookie.get("code", function(stringValue) { //create a number from a hexadecimal code return parseInt(stringValue, 16); });
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).
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:
//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 });
//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 });
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.
//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 });
//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:
var oData = { name: "ace123", age: 22, track: true }; //set a cookie named "user" with subcookies YAHOO.util.Cookie.setSubs("user", oData);
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):
//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); });
//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.
//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;
//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:
//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" });
//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.
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:
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.
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.
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.
be the first to bookmark this page!
All YUI 2.x users should review the YUI 2.8.2 security bulletin, which discusses a vulnerability present in YUI 2.4.0-2.8.1.
Copyright © 2013 Yahoo! Inc. All rights reserved.