标签归档:本地存储

本地存储的兼容解决方案

IE浏览器用userData,主流浏览器用LocalStorage来解决本地存储的需求。userData存储的数据对于同一目录下的地址是可见的,如http://www.zhoumingzhi.com/1/foo.html可以访问到http://www.zhoumingzhi.com/1/bar.html存的数据。而LocalStorage存储的数据对相同域名下的所有页面都是可见的。

var localStorageAdapter = {
    
     storeName: 'NTESBBS',

     isLocalStorage: window.localStorage? true: false,

     dataDOM: this.isLocalStorage? null: (function() {
          try{
               var dataDOM = document.createElement('input'),
                    expires = new Date();

               dataDOM.type = 'hidden';
               dataDOM.style.display = 'none';
               dataDOM.addBehavior('#default#userData');
               document.body.appendChild(dataDOM);
              
               expires.setDate(expires.getDate() + 30);
               dataDOM.expires = expires.toUTCString();

               return dataDOM;
          } catch(ex) {
               return null;
          }
     })(),

     set: function(key, value) {
          var dataDOM = this.dataDOM;

          if(this.isLocalStorage) {
               window.localStorage.setItem(key, value);
          } else {
               if(dataDOM) {
                    dataDOM.load(this.storeName);
                    dataDOM.setAttribute(key, value);
                    dataDOM.save(this.storeName);
               }
          }
     },

     get: function(key) {
          var dataDOM = this.dataDOM;

          if(this.isLocalStorage) {
               return window.localStorage.getItem(key);
          } else {
               if(dataDOM) {
                    dataDOM.load(this.storeName);
                    return dataDOM.getAttribute(key);
               }
          }
     },

     remove: function(key) {
          var dataDOM = this.dataDOM;

          if(this.isLocalStorage) {
               window.localStorage.removeItem(key);
          } else {
               if(dataDOM) {
                    dataDOM.load(this.storeName);
                    dataDOM.removeAttribute(key);
                    dataDOM.save(this.storeName);
               }
          }
     }
}