Home  >  Article  >  Web Front-end  >  JS method to implement local storage of information (based on localStorage and userData)

JS method to implement local storage of information (based on localStorage and userData)

高洛峰
高洛峰Original
2017-02-20 16:34:051357browse

This article mainly introduces the method of JS to implement local storage of information. It implements the local storage function based on localStorage and userData. Friends in need can refer to it.

The example of this article describes the method of JS to implement local storage of information. . Share it with everyone for your reference. The details are as follows:

With the rapid development of WEB applications, local storage of some data has become an important requirement. There are many implementation solutions. The most common one is cookie. Everyone It is often used, but the shortcomings of cookies are obvious. Other solutions include: userData in IE6 and above, globalStorage in Firefox, and local storage in Flash. Except for Flash, the others have some compatibility issues. .

sessionStorage and localStorage

Web Storage actually consists of two parts: sessionStorage and localStorage.

sessionStorage is used to locally store data in a session. These data can only be accessed by pages in the same session and the data will be destroyed when the session ends. Therefore sessionStorage is not a persistent local storage, only session-level storage.

localStorage is used for persistent local storage. Unless the data is actively deleted, the data will never expire.

userData

Syntax:

XML 2f11823406a77a78331405599ab4705f
HTML 50fb392f5c9f23e8d8c1b6195482d7a4
Scripting object .style. behavior = "url('#default#userData')"
object .addBehavior ("#default#userData")

Attribute:

expires Sets or gets the expiration date of userData behavior saved data.
XMLDocument Gets a reference to XML.

Method:

getAttribute() Get the specified attribute value.
load(object) Load the stored object data from the userData storage area.
removeAttribute() Remove the specified attribute of the object.
save(object) Store object data to a userData storage area.
setAttribute() Set the specified attribute value.

localStorage

Method:

localStorage.getItem(key ):Get the value of the local storage of the specified key
localStorage.setItem(key, value):Store the value into the key field
localStorage.removeItem(key):Delete the value stored locally for the specified key

Encapsulation


localData = {
  hname:location.hostname?location.hostname:'localStatus',
  isLocalStorage:window.localStorage?true:false,
  dataDom:null,
  initDom:function(){ //初始化userData
   if(!this.dataDom){
    try{
     this.dataDom = document.createElement('input');//这里使用hidden的input元素
     this.dataDom.type = 'hidden';
     this.dataDom.style.display = "none";
     this.dataDom.addBehavior('#default#userData');//这是userData的语法
     document.body.appendChild(this.dataDom);
     var exDate = new Date();
     exDate = exDate.getDate()+30;
     this.dataDom.expires = exDate.toUTCString();//设定过期时间
    }catch(ex){
     return false;
    }
   }
   return true;
  },
  set:function(key,value){
   if(this.isLocalStorage){
    window.localStorage.setItem(key,value);
   }else{
    if(this.initDom()){
     this.dataDom.load(this.hname);
     this.dataDom.setAttribute(key,value);
     this.dataDom.save(this.hname)
    }
   }
  },
  get:function(key){
   if(this.isLocalStorage){
    return window.localStorage.getItem(key);
   }else{
    if(this.initDom()){
     this.dataDom.load(this.hname);
     return this.dataDom.getAttribute(key);
    }
   }
  },
  remove:function(key){
   if(this.isLocalStorage){
    localStorage.removeItem(key);
   }else{
    if(this.initDom()){
     this.dataDom.load(this.hname);
     this.dataDom.removeAttribute(key);
     this.dataDom.save(this.hname)
    }
   }
  }
}


The method of use is very simple, this section Just set, get, remove.

The demo code involved is as follows:


<script type="text/javascript">
(function() {
  window.localData = {
    hname : location.hostname ? location.hostname : &#39;localStatus&#39;,
    isLocalStorage : window.localStorage ? true : false,
    dataDom : null,
    initDom : function() {
      if (!this.dataDom) {
        try {
          this.dataDom = document.createElement(&#39;input&#39;);
          this.dataDom.type = &#39;hidden&#39;;
          this.dataDom.style.display = "none";
          this.dataDom.addBehavior(&#39;#default#userData&#39;);
          document.body.appendChild(this.dataDom);
          var exDate = new Date();
          exDate = exDate.getDate() + 30;
          this.dataDom.expires = exDate.toUTCString();
        } catch (ex) {
          return false;
        }
      }
      return true;
    },
    set : function(key, value) {
      if (this.isLocalStorage) {
        window.localStorage.setItem(key, value);
      } else {
        if (this.initDom()) {
          this.dataDom.load(this.hname);
          this.dataDom.setAttribute(key, value);
          this.dataDom.save(this.hname)
        }
      }
    },
    get : function(key) {
      if (this.isLocalStorage) {
        return window.localStorage.getItem(key);
      } else {
        if (this.initDom()) {
          this.dataDom.load(this.hname);
          return this.dataDom.getAttribute(key);
        }
      }
    },
    remove : function(key) {
      if (this.isLocalStorage) {
        localStorage.removeItem(key);
      } else {
        if (this.initDom()) {
          this.dataDom.load(this.hname);
          this.dataDom.removeAttribute(key);
          this.dataDom.save(this.hname)
        }
      }
    }
  };
  var text = document.getElementById(&#39;localDataHook&#39;);
  var btn = document.getElementById(&#39;clearBtnHook&#39;);
  window.onbeforeunload = function() {
    localData.set(&#39;beiyuuData&#39;, text.value);
  };
  btn.onclick = function() {
    localData.remove(&#39;beiyuuData&#39;);
    text.value = &#39;&#39;
  };
  if (localData.get(&#39;beiyuuData&#39;)) {
    text.value = localData.get(&#39;beiyuuData&#39;);
  }
})();
</script>


There is also a more practical technology to prevent the page from closing. , display the page closing confirmation pop-up box, the reference code is as follows:


window.onbeforeunload = function() {
  if (!canLeavePage()) {
    return (&#39;确认离开当前页面吗?未保存的数据将会丢失!&#39;);
  }

I hope this article will be helpful to everyone in JavaScript programming.

For more JS methods to implement local storage of information (based on localStorage and userData), please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn