|
| 1 | +<!-- |
| 2 | +Copyright 2013 The Polymer Authors. All rights reserved. |
| 3 | +Use of this source code is governed by a BSD-style |
| 4 | +license that can be found in the LICENSE file. |
| 5 | +--> |
| 6 | +<polymer-element name="polymer-cookie" attributes="name value expires secure domain path max-age"> |
| 7 | + <template> |
| 8 | + <style> |
| 9 | + @host { * { display: none; } } |
| 10 | + </style> |
| 11 | + </template> |
| 12 | + <script> |
| 13 | + (function() { |
| 14 | + var EXPIRE_NOW = 'Thu, 01 Jan 1970 00:00:00 GMT'; |
| 15 | + var FOREVER = 'Fri, 31 Dec 9999 23:59:59 GMT'; |
| 16 | + var cookieProps = ['expires', 'secure', 'max-age', 'domain', 'path']; |
| 17 | + Polymer('polymer-cookie', { |
| 18 | + expires: FOREVER, |
| 19 | + ready: function() { |
| 20 | + this.load(); |
| 21 | + }, |
| 22 | + parseCookie: function() { |
| 23 | + var pairs = document.cookie.split(/\s*;\s*/); |
| 24 | + var map = pairs.map(function(kv) { |
| 25 | + var eq = kv.indexOf('='); |
| 26 | + return { |
| 27 | + name: unescape(kv.slice(0, eq)), |
| 28 | + value: unescape(kv.slice(eq + 1)) |
| 29 | + }; |
| 30 | + }); |
| 31 | + var nom = this.name; |
| 32 | + return map.filter(function(kv){ return kv.name === nom; })[0]; |
| 33 | + }, |
| 34 | + load: function() { |
| 35 | + var kv = this.parseCookie(); |
| 36 | + this.value = kv && kv.value; |
| 37 | + }, |
| 38 | + valueChanged: function() { |
| 39 | + this.expire = FOREVER; |
| 40 | + this.save(); |
| 41 | + }, |
| 42 | + // TODO(dfreedman): collapse these when 'multiple props -> single change function' exists in Polymer |
| 43 | + expiresChanged: function() { |
| 44 | + this.save(); |
| 45 | + }, |
| 46 | + secureChanged: function() { |
| 47 | + this.save(); |
| 48 | + }, |
| 49 | + domainChanged: function() { |
| 50 | + this.save(); |
| 51 | + }, |
| 52 | + pathChanged: function() { |
| 53 | + this.save(); |
| 54 | + }, |
| 55 | + maxAgeChanged: function() { |
| 56 | + this.save(); |
| 57 | + }, |
| 58 | + isCookieStored: function() { |
| 59 | + return Boolean(this.parseCookie()); |
| 60 | + }, |
| 61 | + deleteCookie: function() { |
| 62 | + this.expires = EXPIRE_NOW; |
| 63 | + }, |
| 64 | + prepareProperties: function() { |
| 65 | + var prepared = ''; |
| 66 | + for (var i = 0, k; i < cookieProps.length; i++) { |
| 67 | + k = cookieProps[i]; |
| 68 | + if (this[k]) { |
| 69 | + prepared += (';' + k + '=' + this[k]); |
| 70 | + } |
| 71 | + } |
| 72 | + return prepared; |
| 73 | + }, |
| 74 | + save: function() { |
| 75 | + document.cookie = escape(this.name) + '=' + escape(this.value) + this.prepareProperties(); |
| 76 | + } |
| 77 | + }); |
| 78 | + })(); |
| 79 | + </script> |
| 80 | +</polymer-element> |
0 commit comments