|
/** |
|
* Simple storage interface which uses cookies. Mostly localStorage-compatible, but converts to JSON automatically. |
|
* There are plenty of packages which do this, but none that I could find split the data across multiple cookies if it |
|
* is too big for one cookie. |
|
*/ |
|
window.cookieStorage = { |
|
setItem: function(key, value) { |
|
function splitString(string, size) { |
|
var re = new RegExp('.{1,' + size + '}', 'g'); |
|
return string.match(re); |
|
}; |
|
|
|
cookieStorage.removeItem(key); |
|
|
|
let expiryDate = new Date(2037, 0, 1, 0, 0, 0, 0).toUTCString(); |
|
if (typeof value !== 'string') value = JSON.stringify(value); |
|
|
|
// Max size of cookies is around 4095 bytes, but need padding for base-64 encoding: |
|
// https://en.wikipedia.org/wiki/Base64#Output_padding |
|
let parts = splitString(value, 3000); |
|
|
|
for (var i = 0; i < parts.length; i++) |
|
document.cookie = `${encodeURIComponent(key)}-${i}=${encodeURIComponent(parts[i])};path=/; secure=true; expires=${expiryDate}`; |
|
}, |
|
|
|
getItem: function(key) { |
|
function getCookie(name) { |
|
var i, x, y, cookies = document.cookie.split(';'); |
|
for (i = 0; i < cookies.length; i++) { |
|
x = cookies[i].substr(0, cookies[i].indexOf('=')); |
|
y = cookies[i].substr(cookies[i].indexOf('=') + 1); |
|
x = x.replace(/^\s+|\s+$/g, ''); |
|
if (x == name) |
|
return unescape(y); |
|
} |
|
}; |
|
|
|
function tryParse(value) { |
|
let parsed; |
|
try { |
|
parsed = JSON.parse(value); |
|
} catch (e) { |
|
parsed = value; |
|
} |
|
return parsed; |
|
}; |
|
|
|
var jsonStr = ''; |
|
for (var i = 0; i < 20; i++) { |
|
var cookie = getCookie(`${encodeURIComponent(key)}-${i}`); |
|
if (typeof cookie == 'undefined') break; |
|
jsonStr += cookie; |
|
} |
|
|
|
return tryParse(jsonStr); |
|
}, |
|
|
|
removeItem: function(key) { |
|
for (var i = 0; i < 20; i++) |
|
document.cookie = `${encodeURIComponent(key)}-${i}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`; |
|
}, |
|
}; |