public
Last active

Cross-browser TextStorage Solution

  • Download Gist
textStorage.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
/**
* @ NAME: Cross-browser TextStorage
* @ DESC: text storage solution for your pages
* @ COPY: sofish, http://sofish.de
*/
typeof window.localStorage == 'undefined' && ~function () {
 
var localStorage = window.localStorage = {},
prefix = 'data-userdata',
doc = document,
attrSrc = doc.body,
 
// save attributeNames to <body>'s `data-userdata` attribute
mark = function (key, isRemove, temp, reg) {
 
attrSrc.load(prefix);
temp = attrSrc.getAttribute(prefix) || '';
reg = RegExp('\\b' + key + '\\b,?', 'i');
 
var hasKey = reg.test(temp) ? 1 : 0;
 
temp = isRemove ? temp.replace(reg, '') : hasKey ? temp : temp === '' ? key : temp.split(',').concat(key).join(',');
 
alert(temp);
 
attrSrc.setAttribute(prefix, temp);
attrSrc.save(prefix);
 
};
 
// add IE behavior support
attrSrc.addBehavior('#default#userData');
 
localStorage.getItem = function (key) {
attrSrc.load(key);
return attrSrc.getAttribute(key);
};
 
localStorage.setItem = function (key, value) {
attrSrc.setAttribute(key, value);
attrSrc.save(key);
mark(key);
};
 
localStorage.removeItem = function (key) {
attrSrc.removeAttribute(key);
attrSrc.save(key);
mark(key, 1);
};
 
// clear all attributes on <body> tag that using for textStorage
// and clearing them from the
// 'data-userdata' attribute's value of <body> tag
localStorage.clear = function () {
 
attrSrc.load(prefix);
 
var attrs = attrSrc.getAttribute(prefix).split(','),
len = attrs.length;
 
if (attrs[0] === '') return;
 
for (var i = 0; i < len; i++) {
attrSrc.removeAttribute(attrs[i]);
attrSrc.save(attrs[i]);
};
 
attrSrc.setAttribute(prefix, '');
attrSrc.save(prefix);
 
};
 
}();

I also use this behavior in general, but the approach is useless because IE userData is per folder. This restricts the url structure a lot. My workaround is to have a single Iframe that contains the userData. This way, I have a shared localStorage. The only drawback is that I have to rely on an iframe load event that will usually fire after the main page load event.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.