Internet Explorer localStorage polyfill using userData
Saturday, December 15, 2012·Share·CommentsI have written a localStorage polyfill for Internet Explorer 7 and older using IE's non-standard userData behavior. Below is the code required. It's also available on Github as a gist.
Please note that there are some major differences between userData and localStorage. For example, localStorage persistence is by same-origin policy where as userData persistence is by same-origin plus directory. One workaround to this difference is to use a hidden iFrame with a consistent URL path to load and save persisted data for the parent page.
(function(window, document) { "use strict"; var userData, attr, attributes; if (!window.localStorage && (userData = document.body) && userData.addBehavior) { if (userData.addBehavior("#default#userdata")) { userData.load((attr = "localStorage")); attributes = userData.XMLDocument.documentElement.attributes; window.localStorage = { "length" : attributes.length, "key" : function(idx) { return (idx >= this.length) ? null : attributes[idx].name; }, "getItem" : function(key) { return userData.getAttribute(key); }, "setItem" : function(key, value) { userData.setAttribute(key, value); userData.save(attr); this.length += ((userData.getAttribute(key) === null) ? 1 : 0); }, "removeItem" : function(key) { if (userData.getAttribute(key) !== null) { userData.removeAttribute(key); userData.save(attr); this.length = Math.max(0, this.length - 1); } }, "clear" : function() { while (this.length) { userData.removeAttribute(attributes[--this.length].name); } userData.save(attr); } }; } } })(this, this.document);