| 4 | const __20years = 86400 * 1000 * 365 * 20; |
| 5 | |
| 6 | export default class CookieStorage { |
| 7 | // From https://github.com/Modernizr/Modernizr/blob/f4d3aa0b3c9eeb7338e8d89ed77929a8e969c502/feature-detects/cookies.js#L1 |
| 8 | // try..catch because some in situations `document.cookie` is exposed but throws a |
| 9 | // SecurityError if you try to access it; e.g. documents created from data URIs |
| 10 | // or in sandboxed iframes (depending on flags/context) |
| 11 | public static enabled = R.once((): boolean => { |
| 12 | try { |
| 13 | // Create cookie |
| 14 | document.cookie = 'cookietest=1'; |
| 15 | const ret = document.cookie.indexOf('cookietest=') !== -1; |
| 16 | // Delete cookie |
| 17 | document.cookie = |
| 18 | 'cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT'; |
| 19 | return ret; |
| 20 | } catch (e) { |
| 21 | return false; |
| 22 | } |
| 23 | }); |
| 24 | |
| 25 | public static delete(id: string, domain = '', path = '/') { |
| 26 | if (!CookieStorage.enabled()) { |
| 27 | return; |
| 28 | } |
| 29 | |
| 30 | const expires = new Date(Date.now() - __1day).toUTCString(); |
| 31 | |
| 32 | document.cookie = `${id}=;expires=${expires};domain=${domain};path=${path}`; |
| 33 | } |
| 34 | |
| 35 | public static get(id: string) { |
| 36 | if (!id.length) { |
| 37 | return; |
| 38 | } |
| 39 | |
| 40 | if (!CookieStorage.enabled()) { |
| 41 | return; |
| 42 | } |
| 43 | |
| 44 | id = id.toLowerCase(); |
| 45 | |
| 46 | const cookies = document.cookie.split(';').map(cookie => { |
| 47 | const fragments = cookie.split('='); |
| 48 | |
| 49 | return { |
| 50 | id: fragments[0].trim(), |
| 51 | value: fragments[1] |
| 52 | }; |
| 53 | }); |
| 54 | |
| 55 | return ( |
| 56 | cookies.find(cookie => id === cookie.id.toLocaleLowerCase()) || |
| 57 | ({} as any) |
| 58 | ).value; |
| 59 | } |
| 60 | |
| 61 | public static set(id: string, value: string, domain = '', path = '/') { |
| 62 | if (!CookieStorage.enabled()) { |
| 63 | return; |