Matt's 411

A Web Developer's Blog · Javascript, CSS, HTML and more

  • Internet Explorer localStorage polyfill using userData

    Saturday, December 15, 2012·Share
    • Facebook
    • ·
    • Google Plus
    • ·
    • LinkedIn
    • ·
    • StumbleUpon
    • ·
    • Twitter
    ·Comments

    I 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);
    

Latest Posts

  • Internet Explorer localStorage polyfill using userData
  • Autocomplete with <datalist>
  • Internet Explorer 9 oninput event
  • Grid Updated
  • Canvas Pie and Ring Charts with Tooltips
  • Receive an SMS via Twilio When Your Website Goes Down
  • Comments with Disqus.com
  • Disabling Spellcheck in Textarea Elements
  • Setting the name attribute in IE's DOM
  • Recent Activity
  • Tips for Web Developers
  • Delaying Javascript Event Execution
  • Auto Selecting HTML Text with Javascript