JS Implementation of Local Information Storage Method of Based on localStorage and userData

  • 2021-07-22 08:25:48
  • OfStack

In this paper, an example is given to describe the method of JS to store information locally. Share it for your reference, as follows:

With the rapid development of WEB application, local storage of some data has become an important requirement, and there are many schemes to realize it. The most common one is cookie, which is often used by everyone, but the shortcomings of cookie are obvious. Other schemes, such as userData above IE6, globalStorage below Firefox, and local storage of Flash, have some compatibility problems except Flash.

sessionStorage and localStorage

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

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

localStorage is used for persistent local storage, and data will never expire unless it is actively deleted.

userData

Syntax:

XML < Prefix: CustomTag ID=sID STYLE="behavior:url('#default#userData')" / >
HTML < ELEMENT STYLE="behavior:url('#default#userData')" ID=sID >
Scripting object .style.behavior = "url('#default#userData')"
object .addBehavior ("#default#userData")

Attributes:

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

Methods:

getAttribute() Gets the specified property value.
load(object) Loads stored object data from the userData store.
removeAttribute() Removes the specified property of the object.
save(object) Store object data to 1 userData store.
setAttribute() Sets the specified property value.

localStorage

Methods:

localStorage.getItem(key): Gets the value of the specified key local store
localStorage.setItem(key,value): Store value to key field
localStorage.removeItem(key): Deletes a value that specifies key local storage

Encapsulation


localData = {
  hname:location.hostname?location.hostname:'localStatus',
  isLocalStorage:window.localStorage?true:false,
  dataDom:null,
  initDom:function(){ // Initialization userData
   if(!this.dataDom){
    try{
     this.dataDom = document.createElement('input');// Use here hidden Adj. input Element 
     this.dataDom.type = 'hidden';
     this.dataDom.style.display = "none";
     this.dataDom.addBehavior('#default#userData');// This is userData Grammar of 
     document.body.appendChild(this.dataDom);
     var exDate = new Date();
     exDate = exDate.getDate()+30;
     this.dataDom.expires = exDate.toUTCString();// Set expiration time 
    }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 use method is very simple. This section set, get and remove will be fine.

The demo code involved is as follows:


<script type="text/javascript">
(function() {
  window.localData = {
    hname : location.hostname ? location.hostname : 'localStatus',
    isLocalStorage : window.localStorage ? true : false,
    dataDom : null,
    initDom : function() {
      if (!this.dataDom) {
        try {
          this.dataDom = document.createElement('input');
          this.dataDom.type = 'hidden';
          this.dataDom.style.display = "none";
          this.dataDom.addBehavior('#default#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)
        }
      }
    }
  };
  var text = document.getElementById('localDataHook');
  var btn = document.getElementById('clearBtnHook');
  window.onbeforeunload = function() {
    localData.set('beiyuuData', text.value);
  };
  btn.onclick = function() {
    localData.remove('beiyuuData');
    text.value = ''
  };
  if (localData.get('beiyuuData')) {
    text.value = localData.get('beiyuuData');
  }
})();
</script>

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


window.onbeforeunload = function() {
  if (!canLeavePage()) {
    return (' Are you sure you want to leave the current page? Unsaved data will be lost! ');
  }
};

For more readers interested in JavaScript related content, please check the topics on this site: "javascript Object-Oriented Introduction Tutorial", "JavaScript Search Algorithm Skills Summary", "JavaScript Data Structure and Algorithm Skills Summary", "json Operation Skills Summary in JavaScript", "JavaScript Error and Debugging Skills Summary" and "JavaScript Mathematical Operation Usage Summary"

I hope this article is helpful to everyone's JavaScript programming.


Related articles: