3
Copyright 2011 Yahoo! Inc. All rights reserved.
4
Licensed under the BSD License.
5
http://yuilibrary.com/license/
7
YUI.add('cookie', function(Y) {
10
* Utilities for cookie management
19
//shortcuts to functions
20
isString = L.isString,
21
isObject = L.isObject,
22
isUndefined = L.isUndefined,
23
isFunction = L.isFunction,
24
encode = encodeURIComponent,
25
decode = decodeURIComponent,
27
//shortcut to document
31
* Throws an error message.
33
function error(message){
34
throw new TypeError(message);
38
* Checks the validity of a cookie name.
40
function validateCookieName(name){
41
if (!isString(name) || name === ""){
42
error("Cookie name must be a non-empty string.");
47
* Checks the validity of a subcookie name.
49
function validateSubcookieName(subName){
50
if (!isString(subName) || subName === ""){
51
error("Subcookie name must be a non-empty string.");
62
//-------------------------------------------------------------------------
64
//-------------------------------------------------------------------------
67
* Creates a cookie string that can be assigned into document.cookie.
68
* @param {String} name The name of the cookie.
69
* @param {String} value The value of the cookie.
70
* @param {Boolean} encodeValue True to encode the value, false to leave as-is.
71
* @param {Object} options (Optional) Options for the cookie.
72
* @return {String} The formatted cookie string.
73
* @method _createCookieString
77
_createCookieString : function (name /*:String*/, value /*:Variant*/, encodeValue /*:Boolean*/, options /*:Object*/) /*:String*/ {
79
options = options || {};
81
var text /*:String*/ = encode(name) + "=" + (encodeValue ? encode(value) : value),
82
expires = options.expires,
84
domain = options.domain;
87
if (isObject(options)){
89
if (expires instanceof Date){
90
text += "; expires=" + expires.toUTCString();
94
if (isString(path) && path !== ""){
95
text += "; path=" + path;
99
if (isString(domain) && domain !== ""){
100
text += "; domain=" + domain;
104
if (options.secure === true){
113
* Formats a cookie value for an object containing multiple values.
114
* @param {Object} hash An object of key-value pairs to create a string for.
115
* @return {String} A string suitable for use as a cookie value.
116
* @method _createCookieHashString
120
_createCookieHashString : function (hash /*:Object*/) /*:String*/ {
121
if (!isObject(hash)){
122
error("Cookie._createCookieHashString(): Argument must be an object.");
125
var text /*:Array*/ = [];
127
O.each(hash, function(value, key){
128
if (!isFunction(value) && !isUndefined(value)){
129
text.push(encode(key) + "=" + encode(String(value)));
133
return text.join("&");
137
* Parses a cookie hash string into an object.
138
* @param {String} text The cookie hash string to parse (format: n1=v1&n2=v2).
139
* @return {Object} An object containing entries for each cookie value.
140
* @method _parseCookieHash
144
_parseCookieHash : function (text) {
146
var hashParts = text.split("&"),
151
for (var i=0, len=hashParts.length; i < len; i++){
152
hashPart = hashParts[i].split("=");
153
hash[decode(hashPart[0])] = decode(hashPart[1]);
161
* Parses a cookie string into an object representing all accessible cookies.
162
* @param {String} text The cookie string to parse.
163
* @param {Boolean} shouldDecode (Optional) Indicates if the cookie values should be decoded or not. Default is true.
164
* @return {Object} An object containing entries for each accessible cookie.
165
* @method _parseCookieString
169
_parseCookieString : function (text /*:String*/, shouldDecode /*:Boolean*/) /*:Object*/ {
171
var cookies /*:Object*/ = {};
173
if (isString(text) && text.length > 0) {
175
var decodeValue = (shouldDecode === false ? function(s){return s;} : decode),
176
cookieParts = text.split(/;\s/g),
179
cookieNameValue = NULL;
181
for (var i=0, len=cookieParts.length; i < len; i++){
183
//check for normally-formatted cookie (name-value)
184
cookieNameValue = cookieParts[i].match(/([^=]+)=/i);
185
if (cookieNameValue instanceof Array){
187
cookieName = decode(cookieNameValue[1]);
188
cookieValue = decodeValue(cookieParts[i].substring(cookieNameValue[1].length+1));
190
//intentionally ignore the cookie - the encoding is wrong
193
//means the cookie does not have an "=", so treat it as a boolean flag
194
cookieName = decode(cookieParts[i]);
197
cookies[cookieName] = cookieValue;
206
* Sets the document object that the cookie utility uses for setting
207
* cookies. This method is necessary to ensure that the cookie utility
208
* unit tests can pass even when run on a domain instead of locally.
209
* This method should not be used otherwise; you should use
210
* <code>Y.config.doc</code> to change the document that the cookie
211
* utility uses for everyday purposes.
212
* @param {Object} newDoc The object to use as the document.
217
_setDoc: function(newDoc){
221
//-------------------------------------------------------------------------
223
//-------------------------------------------------------------------------
226
* Determines if the cookie with the given name exists. This is useful for
227
* Boolean cookies (those that do not follow the name=value convention).
228
* @param {String} name The name of the cookie to check.
229
* @return {Boolean} True if the cookie exists, false if not.
233
exists: function(name) {
235
validateCookieName(name); //throws error
237
var cookies = this._parseCookieString(doc.cookie, true);
239
return cookies.hasOwnProperty(name);
243
* Returns the cookie value for the given name.
244
* @param {String} name The name of the cookie to retrieve.
245
* @param {Function|Object} options (Optional) An object containing one or more
246
* cookie options: raw (true/false) and converter (a function).
247
* The converter function is run on the value before returning it. The
248
* function is not used if the cookie doesn't exist. The function can be
249
* passed instead of the options object for backwards compatibility. When
250
* raw is set to true, the cookie value is not URI decoded.
251
* @return {Variant} If no converter is specified, returns a string or null if
252
* the cookie doesn't exist. If the converter is specified, returns the value
253
* returned from the converter or null if the cookie doesn't exist.
257
get : function (name, options) {
259
validateCookieName(name); //throws error
265
//if options is a function, then it's the converter
266
if (isFunction(options)) {
269
} else if (isObject(options)) {
270
converter = options.converter;
275
cookies = this._parseCookieString(doc.cookie, !options.raw);
276
cookie = cookies[name];
278
//should return null, not undefined if the cookie doesn't exist
279
if (isUndefined(cookie)) {
283
if (!isFunction(converter)){
286
return converter(cookie);
291
* Returns the value of a subcookie.
292
* @param {String} name The name of the cookie to retrieve.
293
* @param {String} subName The name of the subcookie to retrieve.
294
* @param {Function} converter (Optional) A function to run on the value before returning
295
* it. The function is not used if the cookie doesn't exist.
296
* @return {Variant} If the cookie doesn't exist, null is returned. If the subcookie
297
* doesn't exist, null if also returned. If no converter is specified and the
298
* subcookie exists, a string is returned. If a converter is specified and the
299
* subcookie exists, the value returned from the converter is returned.
303
getSub : function (name /*:String*/, subName /*:String*/, converter /*:Function*/) /*:Variant*/ {
305
var hash /*:Variant*/ = this.getSubs(name);
309
validateSubcookieName(subName); //throws error
311
if (isUndefined(hash[subName])){
315
if (!isFunction(converter)){
316
return hash[subName];
318
return converter(hash[subName]);
327
* Returns an object containing name-value pairs stored in the cookie with the given name.
328
* @param {String} name The name of the cookie to retrieve.
329
* @return {Object} An object of name-value pairs if the cookie with the given name
330
* exists, null if it does not.
334
getSubs : function (name) {
336
validateCookieName(name); //throws error
338
var cookies = this._parseCookieString(doc.cookie, false);
339
if (isString(cookies[name])){
340
return this._parseCookieHash(cookies[name]);
346
* Removes a cookie from the machine by setting its expiration date to
347
* sometime in the past.
348
* @param {String} name The name of the cookie to remove.
349
* @param {Object} options (Optional) An object containing one or more
350
* cookie options: path (a string), domain (a string),
351
* and secure (true/false). The expires option will be overwritten
353
* @return {String} The created cookie string.
357
remove : function (name, options) {
359
validateCookieName(name); //throws error
362
options = Y.merge(options || {}, {
367
return this.set(name, "", options);
371
* Removes a sub cookie with a given name.
372
* @param {String} name The name of the cookie in which the subcookie exists.
373
* @param {String} subName The name of the subcookie to remove.
374
* @param {Object} options (Optional) An object containing one or more
375
* cookie options: path (a string), domain (a string), expires (a Date object),
376
* removeIfEmpty (true/false), and secure (true/false). This must be the same
377
* settings as the original subcookie.
378
* @return {String} The created cookie string.
382
removeSub : function(name, subName, options) {
384
validateCookieName(name); //throws error
386
validateSubcookieName(subName); //throws error
388
options = options || {};
390
//get all subcookies for this cookie
391
var subs = this.getSubs(name);
393
//delete the indicated subcookie
394
if (isObject(subs) && subs.hasOwnProperty(subName)){
395
delete subs[subName];
397
if (!options.removeIfEmpty) {
400
return this.setSubs(name, subs, options);
402
//reset the cookie if there are subcookies left, else remove
403
for (var key in subs){
404
if (subs.hasOwnProperty(key) && !isFunction(subs[key]) && !isUndefined(subs[key])){
405
return this.setSubs(name, subs, options);
409
return this.remove(name, options);
418
* Sets a cookie with a given name and value.
419
* @param {String} name The name of the cookie to set.
420
* @param {Variant} value The value to set for the cookie.
421
* @param {Object} options (Optional) An object containing one or more
422
* cookie options: path (a string), domain (a string), expires (a Date object),
423
* secure (true/false), and raw (true/false). Setting raw to true indicates
424
* that the cookie should not be URI encoded before being set.
425
* @return {String} The created cookie string.
429
set : function (name, value, options) {
431
validateCookieName(name); //throws error
433
if (isUndefined(value)){
434
error("Cookie.set(): Value cannot be undefined.");
437
options = options || {};
439
var text = this._createCookieString(name, value, !options.raw, options);
445
* Sets a sub cookie with a given name to a particular value.
446
* @param {String} name The name of the cookie to set.
447
* @param {String} subName The name of the subcookie to set.
448
* @param {Variant} value The value to set.
449
* @param {Object} options (Optional) An object containing one or more
450
* cookie options: path (a string), domain (a string), expires (a Date object),
451
* and secure (true/false).
452
* @return {String} The created cookie string.
456
setSub : function (name, subName, value, options) {
458
validateCookieName(name); //throws error
460
validateSubcookieName(subName); //throws error
462
if (isUndefined(value)){
463
error("Cookie.setSub(): Subcookie value cannot be undefined.");
466
var hash = this.getSubs(name);
468
if (!isObject(hash)){
472
hash[subName] = value;
474
return this.setSubs(name, hash, options);
479
* Sets a cookie with a given name to contain a hash of name-value pairs.
480
* @param {String} name The name of the cookie to set.
481
* @param {Object} value An object containing name-value pairs.
482
* @param {Object} options (Optional) An object containing one or more
483
* cookie options: path (a string), domain (a string), expires (a Date object),
484
* and secure (true/false).
485
* @return {String} The created cookie string.
489
setSubs : function (name, value, options) {
491
validateCookieName(name); //throws error
493
if (!isObject(value)){
494
error("Cookie.setSubs(): Cookie value must be an object.");
497
var text /*:String*/ = this._createCookieString(name, this._createCookieHashString(value), false, options);
505
}, '3.4.1' ,{requires:['yui-base']});