5
<title>Cookie Utility</title>
6
<link rel="stylesheet" href="http://yui.yahooapis.com/3.4.0pr3/build/cssgrids/grids-min.css">
7
<link rel="stylesheet" href="../assets/css/main.css">
8
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
9
<script src="../../build/yui/yui-min.js"></script>
14
<h1>Cookie Utility</h1>
17
<a href="#toc" class="jump">Jump to Table of Contents</a>
21
<div id="main" class="yui3-u">
22
<div class="content"><div class="intro">
23
<p>The YUI Cookie utility provides a simple API for interacting with cookies, including the creation and manipulation of subcookies.</p>
25
<p><strong>Note about HTTPOnly Cookies:</strong> 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 setting HTTPOnly cookies by JavaScript, we will revisit adding support for it in the Cookie utility.</p>
28
<h2 id="getting-started">Getting Started</h2>
31
To include the source files for Cookie Utility and its dependencies, first load
32
the YUI seed file if you haven't already loaded it.
35
<pre class="code prettyprint"><script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script></pre>
39
Next, create a new YUI instance for your application and populate it with the
40
modules you need by specifying them as arguments to the <code>YUI().use()</code> method.
41
YUI will automatically load any dependencies required by the modules you
45
<pre class="code prettyprint">// Create a new YUI instance and populate it with the required modules.
46
YUI().use('cookie', function (Y) {
47
// Cookie Utility is available and ready for use. Add implementation
48
// code here.
53
For more information on creating YUI instances and on the
54
<a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_use"><code>use()</code> method</a>, see the
55
documentation for the <a href="../yui/index.html">YUI Global object</a>.
59
<h2 id="using">Using the Cookie Utility</h2>
61
<h3 id="create">Creating Cookies</h3>
63
<p>The simplest way to create a cookie is to provide a name and a value to the <code>set()</code> method:</p>
65
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
66
YUI().use('cookie', function(Y) {
67
Y.Cookie.set("name", "value");
71
<p>This example creates a cookie called "name" that has a value of "value". Since
72
this cookie is created with all of the default settings, it becomes a session cookie.</p>
74
<p>There is a third argument for <code>set()</code>, which is an object containing additional settings for the cookie. To create a persistent cookie, you can specify an expiration date by supplying a <code>Date</code> object:</p>
76
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
77
YUI().use('cookie', function(Y) {
78
Y.Cookie.set("name", "value", { expires: new Date("January 12, 2025") });
82
<p>By providing an "expires" option in the third argument, the cookie persists until the given date. In this example,
83
the cookie will remain until January 12, 2025. The value for "expires" must be a <code>Date</code> object, otherwise
86
<p>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:</p>
88
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
89
YUI().use('cookie', function(Y) {
90
Y.Cookie.set("name", "value", {
91
path: "/", //all pages
92
domain: "yahoo.com" //any subdomain of yahoo.com, including www.yahoo.com
97
<p>In this example, a cookie is created that can be accessed from all pages on a yahoo.com subdomain. This cookie would
98
then be accessible from pages on <a href="http://sports.yahoo.com">sports.yahoo.com</a> as well as <a href="http://www.yahoo.com">www.yahoo.com</a>.
99
The "path" and "domain" options need not be used together; they may be used independently as well.</p>
101
<p>The last option is "secure", which indicates that the cookie should only be accessible via SSL on a page
102
using the HTTPS protocol. All other aspects of the cookie remain the same based on the other options provided. To set a
103
secure cookie, use the "secure" option:</p>
105
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
106
YUI().use('cookie', function(Y){
107
Y.Cookie.set("name", "value", { secure: true });
111
<p>This code creates a secure cookie by setting the "secure" option to <code>true</code>. 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.</p>
113
<p>There is one more option called "raw". When this option is specified, the cookie will not be URL-encoded before being set. Setting a "raw" cookie typically means that you have specialized server-side logic to deal with cookies that aren't URL-encoded. This is considered an advanced option that should only be used when necessary. Example usage:</p>
115
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
116
YUI().use('cookie', function(Y){
117
Y.Cookie.set("name", "value", { raw: true });
121
<h3 id="read">Reading Cookies</h3>
123
<p>The <code>get()</code> method retrieves cookies that are accessible by the current page. If a cookie doesn't exist, <code>get()</code> returns <code>null</code>.</p>
125
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
126
YUI().use('cookie', function(Y){
127
var value = Y.Cookie.get("name");
131
<p>This example retrieves the cookie called "name" and stores its value in the variable <code>value</code>. By default, values returned by <code>get()</code> are strings (if the cookie exists) or <code>null</code> (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 <code>Number()</code> function:</p>
133
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
134
YUI().use('cookie', function(Y){
135
var value = Y.Cookie.get("age", Number);
139
<p>In this code, the returned cookie value will be a number if the cookie exists (it will still be <code>null</code> if the cookie doesn't exist). Other native functions that convert values are <code>Boolean()</code> and <code>Date</code>, or you can define your own conversion function:</p>
141
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
142
YUI().use('cookie', function(Y){
143
var value = Y.Cookie.get("code", function(stringValue){
144
return parseInt(stringValue, 16); // Create a number from a hexadecimal code
149
<p>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 <code>parseInt()</code> to convert the value into a number. Note that the conversion function is never called if the cookie doesn't exist (<code>get()</code> always returns <code>null</code> when the cookie doesn't exist).</p>
151
<p>The second argument can optionally be an object if you'd like to read a raw cookie. As with, writing cookies, it's possible to read a cookie without URL-decoding the value. To specify this, the second argument should be an object, such as:</p>
153
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
154
YUI().use('cookie', function(Y){
155
var value = Y.Cookie.get("code", { raw: true });
159
<p>If you'd like to use a converter on a raw cookie, you can specify this using the "converter" option:</p>
161
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
162
YUI().use('cookie', function(Y){
163
var value = Y.Cookie.get("code", {
165
converter: function(stringValue){
166
return parseInt(stringValue, 16); // Create a number from a hexadecimal code
172
<h3 id="delete">Deleting Cookies</h3>
174
<p>When a cookie is no longer need, it can be removed from the browser by calling the <code>remove()</code> 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 <code>domain</code> property of "yahoo.com" can only be deleted by also specifying the <code>domain</code> property as "yahoo.com". Examples:</p>
176
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
177
YUI().use('cookie', function(Y){
178
//delete the cookie named "code"
179
Y.Cookie.remove("code");
181
//delete the cookie named "info" on the "yahoo.com" domain
182
Y.Cookie.remove("info", { domain: "yahoo.com" });
184
//delete a secure cookie named "username"
185
Y.Cookie.remove("username", { secure: true });
189
<h3 id="sub">Subcookies</h3>
191
<p>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.</p>
193
<p>A subcookie string looks similar to a URL and takes the following form:</p>
195
<p><code>cookiename=name1=value1&name2=value2&name3=value3</code></p>
197
<p>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 <code>setSub()</code> 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.</p>
199
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
200
YUI().use('cookie', function(Y){
202
//set a cookie named "name" with a subcookie named "subname" whose value is "value"
203
Y.Cookie.setSub("name", "subname", "value");
205
//set a second subcookie on "name", with a name of "subname2" and a value of "value2"
206
Y.Cookie.setSub("name", "subname2", "value2");
208
//set subcookie on the "yahoo.com" domain
209
Y.Cookie.setSub("info", "age", 22, { domain: "yahoo.com" });
211
//set subcookie to a secure cookie named "user"
212
Y.Cookie.setSub("user", "name", "ace123", { secure:true });
216
<p>It's possible to set the entire contents of a subcookie by using the <code>setSubs()</code> method, which accepts three arguments:
217
the name of the cookie, and object containing name-value pairs, and an optional cookie options object. For instance, this code
218
sets three subcookies at once:</p>
220
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
221
YUI().use('cookie', function(Y){
224
name: "ace123",
229
//set a cookie named "user" with subcookies
230
Y.Cookie.setSubs("user", data);
235
<p>Note that calls to <code>setSubs()</code> will always completely overwrite the cookie.</p>
237
<p>To retrieve subcookie values, there are two methods. The first is <code>getSub()</code>, which retrieves a single subcookie value.
238
This method accepts three arguments: the cookie name, the subcookie name, and an optional converter function. As with <code>get()</code>,
239
the converter function changes the data or type of data retrieved from the cookie before it's returned (and isn't called at all
240
if the cookie or subcookie doesn't exist):</p>
242
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
243
YUI().use('cookie', function(Y){
245
//get subcookie
246
var stringValue = Y.Cookie.getSub("name", "subname");
248
//get subcookie and convert to number
249
var numberValue = Y.Cookie.getSub("user", "age", Number);
251
//get subcookie and convert from hex code to decimal number
252
var integerValue = Y.Cookie.getSub("settings", "bgcolor", function(stringValue){
253
return parseInt(stringValue, 16); // Create a number from a hexadecimal code
259
<p>The second method to retrieve subcookies is <code>getSubs()</code>, which retrieves all subcookies and returns an object
260
with name-value pairs for each subcookie. The <code>getSubs()</code> method takes a single argument, the name of the cookie
261
containing subcookies to retrieve. The returned value is either an object or <code>null</code> if the cookie doesn't exist.</p>
263
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
264
YUI().use('cookie', function(Y){
266
//get all subcookies
267
var data = Y.Cookie.getSubs("name");
268
var subValue = data.subname;
270
//get all subcookies
271
var user = Y.Cookie.getSubs("user");
272
var userName = user.name;
277
<p>Removing subcookies is accomplished using the <code>removeSub()</code> 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
278
as when the cookie was originally created. Example:</p>
280
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
281
YUI().use('cookie', function(Y){
283
//set subcookie on the "yahoo.com" domain
284
Y.Cookie.setSub("info", "age", 22, { domain: "yahoo.com" });
286
//remove the subcookie
287
Y.Cookie.removeSub("info", "age", { domain: "yahoo.com" });
291
<p>Removing a subcookie keeps all other subcookies for that cookie intact. If you want to remove all subcookies, it's easiest to use <code>remove()</code> to remove the entire cookie.</p>
293
<p>When the last subcookie is removed, the overall cookie still remains. If you'd like to remove the cookie when the last subcookie is removed, then specify the "removeIfEmpty" option:</p>
295
<pre class="code prettyprint">// Create a YUI instance and use the cookie module.
296
YUI().use('cookie', function(Y){
298
//remove the subcookie
299
Y.Cookie.removeSub("info", "age", { removeIfEmpty: true });
305
<div id="sidebar" class="yui3-u">
307
<div id="toc" class="sidebox">
309
<h2 class="no-toc">Table of Contents</h2>
315
<a href="#getting-started">Getting Started</a>
318
<a href="#using">Using the Cookie Utility</a>
321
<a href="#create">Creating Cookies</a>
324
<a href="#read">Reading Cookies</a>
327
<a href="#delete">Deleting Cookies</a>
330
<a href="#sub">Subcookies</a>
340
<div class="sidebox">
342
<h2 class="no-toc">Examples</h2>
346
<ul class="examples">
349
<li data-description="Demonstrates basic usage of the Cookie utility for reading and writing cookies.">
350
<a href="cookie-simple-example.html">Simple Cookie Example</a>
355
<li data-description="Demonstrates using the Cookie utility to get, set and remove cookies.">
356
<a href="cookie-advanced-example.html">Advanced Cookie Example</a>
361
<li data-description="Demonstrates using the Cookie utility to get and set subcookies.">
362
<a href="cookie-subcookie-example.html">Subcookie Example</a>
376
<script src="../assets/vendor/prettify/prettify-min.js"></script>
377
<script>prettyPrint();</script>