技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> JavaScript --> 本地存储的兼容解决方案

本地存储的兼容解决方案

浏览:1620次  出处信息

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

建议继续学习:

  1. HTML5本地存储初探    (阅读:2904)
  2. HTML5实战之本地存储(1)    (阅读:2600)
  3. HTML5实战之本地存储(3) - 请求同步    (阅读:2431)
  4. JavaScript本地存储实践(html5的localStorage和ie的userData)    (阅读:2239)
  5. HTML5实战之本地存储(2)    (阅读:1993)
  6. 关于html5本地存储    (阅读:1205)
  7. 实现 go 的 goroutine 本地存储又一种方式    (阅读:661)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1