2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 YUI.add('cookie', function(Y) {
11 * Utilities for cookie management
20 //shortcuts to functions
21 isString = L.isString,
22 isObject = L.isObject,
23 isUndefined = L.isUndefined,
24 isFunction = L.isFunction,
25 encode = encodeURIComponent,
26 decode = decodeURIComponent,
28 //shortcut to document
32 * Throws an error message.
34 function error(message){
35 throw new TypeError(message);
39 * Checks the validity of a cookie name.
41 function validateCookieName(name){
42 if (!isString(name) || name === ""){
43 error("Cookie name must be a non-empty string.");
48 * Checks the validity of a subcookie name.
50 function validateSubcookieName(subName){
51 if (!isString(subName) || subName === ""){
52 error("Subcookie name must be a non-empty string.");
63 //-------------------------------------------------------------------------
65 //-------------------------------------------------------------------------
68 * Creates a cookie string that can be assigned into document.cookie.
69 * @param {String} name The name of the cookie.
70 * @param {String} value The value of the cookie.
71 * @param {Boolean} encodeValue True to encode the value, false to leave as-is.
72 * @param {Object} options (Optional) Options for the cookie.
73 * @return {String} The formatted cookie string.
74 * @method _createCookieString
78 _createCookieString : function (name /*:String*/, value /*:Variant*/, encodeValue /*:Boolean*/, options /*:Object*/) /*:String*/ {
80 options = options || {};
82 var text /*:String*/ = encode(name) + "=" + (encodeValue ? encode(value) : value),
83 expires = options.expires,
85 domain = options.domain;
88 if (isObject(options)){
90 if (expires instanceof Date){
91 text += "; expires=" + expires.toUTCString();
95 if (isString(path) && path !== ""){
96 text += "; path=" + path;
100 if (isString(domain) && domain !== ""){
101 text += "; domain=" + domain;
105 if (options.secure === true){
114 * Formats a cookie value for an object containing multiple values.
115 * @param {Object} hash An object of key-value pairs to create a string for.
116 * @return {String} A string suitable for use as a cookie value.
117 * @method _createCookieHashString
121 _createCookieHashString : function (hash /*:Object*/) /*:String*/ {
122 if (!isObject(hash)){
123 error("Cookie._createCookieHashString(): Argument must be an object.");
126 var text /*:Array*/ = [];
128 O.each(hash, function(value, key){
129 if (!isFunction(value) && !isUndefined(value)){
130 text.push(encode(key) + "=" + encode(String(value)));
134 return text.join("&");
138 * Parses a cookie hash string into an object.
139 * @param {String} text The cookie hash string to parse (format: n1=v1&n2=v2).
140 * @return {Object} An object containing entries for each cookie value.
141 * @method _parseCookieHash
145 _parseCookieHash : function (text) {
147 var hashParts = text.split("&"),
152 for (var i=0, len=hashParts.length; i < len; i++){
153 hashPart = hashParts[i].split("=");
154 hash[decode(hashPart[0])] = decode(hashPart[1]);
162 * Parses a cookie string into an object representing all accessible cookies.
163 * @param {String} text The cookie string to parse.
164 * @param {Boolean} shouldDecode (Optional) Indicates if the cookie values should be decoded or not. Default is true.
165 * @return {Object} An object containing entries for each accessible cookie.
166 * @method _parseCookieString
170 _parseCookieString : function (text /*:String*/, shouldDecode /*:Boolean*/) /*:Object*/ {
172 var cookies /*:Object*/ = {};
174 if (isString(text) && text.length > 0) {
176 var decodeValue = (shouldDecode === false ? function(s){return s;} : decode),
177 cookieParts = text.split(/;\s/g),
180 cookieNameValue = NULL;
182 for (var i=0, len=cookieParts.length; i < len; i++){
184 //check for normally-formatted cookie (name-value)
185 cookieNameValue = cookieParts[i].match(/([^=]+)=/i);
186 if (cookieNameValue instanceof Array){
188 cookieName = decode(cookieNameValue[1]);
189 cookieValue = decodeValue(cookieParts[i].substring(cookieNameValue[1].length+1));
191 //intentionally ignore the cookie - the encoding is wrong
194 //means the cookie does not have an "=", so treat it as a boolean flag
195 cookieName = decode(cookieParts[i]);
198 cookies[cookieName] = cookieValue;
207 * Sets the document object that the cookie utility uses for setting
208 * cookies. This method is necessary to ensure that the cookie utility
209 * unit tests can pass even when run on a domain instead of locally.
210 * This method should not be used otherwise; you should use
211 * <code>Y.config.doc</code> to change the document that the cookie
212 * utility uses for everyday purposes.
213 * @param {Object} newDoc The object to use as the document.
218 _setDoc: function(newDoc){
222 //-------------------------------------------------------------------------
224 //-------------------------------------------------------------------------
227 * Determines if the cookie with the given name exists. This is useful for
228 * Boolean cookies (those that do not follow the name=value convention).
229 * @param {String} name The name of the cookie to check.
230 * @return {Boolean} True if the cookie exists, false if not.
234 exists: function(name) {
236 validateCookieName(name); //throws error
238 var cookies = this._parseCookieString(doc.cookie, true);
240 return cookies.hasOwnProperty(name);
244 * Returns the cookie value for the given name.
245 * @param {String} name The name of the cookie to retrieve.
246 * @param {Function|Object} options (Optional) An object containing one or more
247 * cookie options: raw (true/false) and converter (a function).
248 * The converter function is run on the value before returning it. The
249 * function is not used if the cookie doesn't exist. The function can be
250 * passed instead of the options object for backwards compatibility. When
251 * raw is set to true, the cookie value is not URI decoded.
252 * @return {Variant} If no converter is specified, returns a string or null if
253 * the cookie doesn't exist. If the converter is specified, returns the value
254 * returned from the converter or null if the cookie doesn't exist.
258 get : function (name, options) {
260 validateCookieName(name); //throws error
266 //if options is a function, then it's the converter
267 if (isFunction(options)) {
270 } else if (isObject(options)) {
271 converter = options.converter;
276 cookies = this._parseCookieString(doc.cookie, !options.raw);
277 cookie = cookies[name];
279 //should return null, not undefined if the cookie doesn't exist
280 if (isUndefined(cookie)) {
284 if (!isFunction(converter)){
287 return converter(cookie);
292 * Returns the value of a subcookie.
293 * @param {String} name The name of the cookie to retrieve.
294 * @param {String} subName The name of the subcookie to retrieve.
295 * @param {Function} converter (Optional) A function to run on the value before returning
296 * it. The function is not used if the cookie doesn't exist.
297 * @return {Variant} If the cookie doesn't exist, null is returned. If the subcookie
298 * doesn't exist, null if also returned. If no converter is specified and the
299 * subcookie exists, a string is returned. If a converter is specified and the
300 * subcookie exists, the value returned from the converter is returned.
304 getSub : function (name /*:String*/, subName /*:String*/, converter /*:Function*/) /*:Variant*/ {
306 var hash /*:Variant*/ = this.getSubs(name);
310 validateSubcookieName(subName); //throws error
312 if (isUndefined(hash[subName])){
316 if (!isFunction(converter)){
317 return hash[subName];
319 return converter(hash[subName]);
328 * Returns an object containing name-value pairs stored in the cookie with the given name.
329 * @param {String} name The name of the cookie to retrieve.
330 * @return {Object} An object of name-value pairs if the cookie with the given name
331 * exists, null if it does not.
335 getSubs : function (name) {
337 validateCookieName(name); //throws error
339 var cookies = this._parseCookieString(doc.cookie, false);
340 if (isString(cookies[name])){
341 return this._parseCookieHash(cookies[name]);
347 * Removes a cookie from the machine by setting its expiration date to
348 * sometime in the past.
349 * @param {String} name The name of the cookie to remove.
350 * @param {Object} options (Optional) An object containing one or more
351 * cookie options: path (a string), domain (a string),
352 * and secure (true/false). The expires option will be overwritten
354 * @return {String} The created cookie string.
358 remove : function (name, options) {
360 validateCookieName(name); //throws error
363 options = Y.merge(options || {}, {
368 return this.set(name, "", options);
372 * Removes a sub cookie with a given name.
373 * @param {String} name The name of the cookie in which the subcookie exists.
374 * @param {String} subName The name of the subcookie to remove.
375 * @param {Object} options (Optional) An object containing one or more
376 * cookie options: path (a string), domain (a string), expires (a Date object),
377 * removeIfEmpty (true/false), and secure (true/false). This must be the same
378 * settings as the original subcookie.
379 * @return {String} The created cookie string.
383 removeSub : function(name, subName, options) {
385 validateCookieName(name); //throws error
387 validateSubcookieName(subName); //throws error
389 options = options || {};
391 //get all subcookies for this cookie
392 var subs = this.getSubs(name);
394 //delete the indicated subcookie
395 if (isObject(subs) && subs.hasOwnProperty(subName)){
396 delete subs[subName];
398 if (!options.removeIfEmpty) {
401 return this.setSubs(name, subs, options);
403 //reset the cookie if there are subcookies left, else remove
404 for (var key in subs){
405 if (subs.hasOwnProperty(key) && !isFunction(subs[key]) && !isUndefined(subs[key])){
406 return this.setSubs(name, subs, options);
410 return this.remove(name, options);
419 * Sets a cookie with a given name and value.
420 * @param {String} name The name of the cookie to set.
421 * @param {Variant} value The value to set for the cookie.
422 * @param {Object} options (Optional) An object containing one or more
423 * cookie options: path (a string), domain (a string), expires (a Date object),
424 * secure (true/false), and raw (true/false). Setting raw to true indicates
425 * that the cookie should not be URI encoded before being set.
426 * @return {String} The created cookie string.
430 set : function (name, value, options) {
432 validateCookieName(name); //throws error
434 if (isUndefined(value)){
435 error("Cookie.set(): Value cannot be undefined.");
438 options = options || {};
440 var text = this._createCookieString(name, value, !options.raw, options);
446 * Sets a sub cookie with a given name to a particular value.
447 * @param {String} name The name of the cookie to set.
448 * @param {String} subName The name of the subcookie to set.
449 * @param {Variant} value The value to set.
450 * @param {Object} options (Optional) An object containing one or more
451 * cookie options: path (a string), domain (a string), expires (a Date object),
452 * and secure (true/false).
453 * @return {String} The created cookie string.
457 setSub : function (name, subName, value, options) {
459 validateCookieName(name); //throws error
461 validateSubcookieName(subName); //throws error
463 if (isUndefined(value)){
464 error("Cookie.setSub(): Subcookie value cannot be undefined.");
467 var hash = this.getSubs(name);
469 if (!isObject(hash)){
473 hash[subName] = value;
475 return this.setSubs(name, hash, options);
480 * Sets a cookie with a given name to contain a hash of name-value pairs.
481 * @param {String} name The name of the cookie to set.
482 * @param {Object} value An object containing name-value pairs.
483 * @param {Object} options (Optional) An object containing one or more
484 * cookie options: path (a string), domain (a string), expires (a Date object),
485 * and secure (true/false).
486 * @return {String} The created cookie string.
490 setSubs : function (name, value, options) {
492 validateCookieName(name); //throws error
494 if (!isObject(value)){
495 error("Cookie.setSubs(): Cookie value must be an object.");
498 var text /*:String*/ = this._createCookieString(name, this._createCookieHashString(value), false, options);
507 }, '3.3.0' ,{requires:['yui-base']});