Fixes #1155 - Cookie requires Browser for the document object in the options. Otherwi...
[mootools/dkf.git] / Source / Utilities / Cookie.js
blob07ce418cef0ff42de6b322fa608919d07a937e2a
1 /*
2 ---
4 name: Cookie
6 description: Class for creating, reading, and deleting browser Cookies.
8 license: MIT-style license.
10 credits:
11   - Based on the functions by Peter-Paul Koch (http://quirksmode.org).
13 requires: [Options, Browser]
15 provides: Cookie
17 ...
20 var Cookie = new Class({
22         Implements: Options,
24         options: {
25                 path: '/',
26                 domain: false,
27                 duration: false,
28                 secure: false,
29                 document: document,
30                 encode: true
31         },
33         initialize: function(key, options){
34                 this.key = key;
35                 this.setOptions(options);
36         },
38         write: function(value){
39                 if (this.options.encode) value = encodeURIComponent(value);
40                 if (this.options.domain) value += '; domain=' + this.options.domain;
41                 if (this.options.path) value += '; path=' + this.options.path;
42                 if (this.options.duration){
43                         var date = new Date();
44                         date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000);
45                         value += '; expires=' + date.toGMTString();
46                 }
47                 if (this.options.secure) value += '; secure';
48                 this.options.document.cookie = this.key + '=' + value;
49                 return this;
50         },
52         read: function(){
53                 var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)');
54                 return (value) ? decodeURIComponent(value[1]) : null;
55         },
57         dispose: function(){
58                 new Cookie(this.key, Object.merge({}, this.options, {duration: -1})).write('');
59                 return this;
60         }
62 });
64 Cookie.write = function(key, value, options){
65         return new Cookie(key, options).write(value);
68 Cookie.read = function(key){
69         return new Cookie(key).read();
72 Cookie.dispose = function(key, options){
73         return new Cookie(key, options).dispose();