Skip to content
This repository was archived by the owner on Mar 13, 2018. It is now read-only.

Commit 0db6998

Browse files
committed
Add <polymer-cookie> element wrapping over the Cookie API
1 parent 6b08976 commit 0db6998

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

polymer-cookie/polymer-cookie.html

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
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+
// TODO(dfreedman): collapse these when 'multiple props -> single change function' exists in Polymer
39+
valueChanged: function() {
40+
this.save();
41+
},
42+
expiresChanged: function() {
43+
this.save();
44+
},
45+
secureChanged: function() {
46+
this.save();
47+
},
48+
domainChanged: function() {
49+
this.save();
50+
},
51+
pathChanged: function() {
52+
this.save();
53+
},
54+
maxAgeChanged: function() {
55+
this.save();
56+
},
57+
isCookieStored: function() {
58+
return Boolean(this.parseCookie());
59+
},
60+
deleteCookie: function() {
61+
this.expires = EXPIRE_NOW;
62+
},
63+
prepareProperties: function() {
64+
var prepared = '';
65+
for (var i = 0, k; i < cookieProps.length; i++) {
66+
k = cookieProps[i];
67+
if (this[k]) {
68+
prepared += ';' + escape(k) + '=' escape(this[k]);
69+
}
70+
}
71+
return prepared;
72+
},
73+
save: function() {
74+
document.cookie = escape(this.name) + '=' + escape(this.value) + this.prepareProperties();
75+
}
76+
});
77+
})();
78+
</script>
79+
</polymer-element>

0 commit comments

Comments
 (0)