English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

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

This article describes the method of implementing local storage information with JS. Shared for everyone's reference, as follows:

The rapid development of WEB applications has made local storage of some data an important requirement, and there are many solutions to implement it. The most common one is cookie, which everyone often uses, but the disadvantages of cookies are obvious. Other solutions include: IE6The above userData, Firefox's globalStorage, and Flash's local storage, except for Flash, all have some compatibility issues.

sessionStorage and localStorage

Web Storage is actually composed of two parts: sessionStorage and localStorage.

sessionStorage is used to store data for a local session. This data can only be accessed on the same session pages and is 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. Unless the data is actively deleted, it will never expire.

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")

Properties:

expires sets or retrieves the expiration date of the data saved in userData behavior.
XMLDocument Retrieves the reference to XML.

Method:

getAttribute() Retrieves the specified attribute value.
load(object) Loads the stored object data from the userData storage area.
removeAttribute() Removes the specified attribute from the object.
save(object) Stores the object data in a userData storage area.
setAttribute() Sets the specified attribute value.

localStorage

Method:

localStorage.getItem(key): Retrieves the value of the specified key from local storage
localStorage.setItem(key,value): Stores the value in the key field
localStorage.removeItem(key): Deletes the value of the specified key from local storage

Encapsulation

localData = {
  hname:location.hostname&63;location.hostname:'localStatus',
  ;window.localStorage&63;true:false,
  dataDom:null,
  initDom:function(){ //Initialize userData
   if(!this.dataDom){
    try{
     this.dataDom = document.createElement('input');//Here, the hidden input element is used
     this.dataDom.type = 'hidden';
     this.dataDom.style.display = "none";
     this.dataDom.addBehavior('#default#userData');//This is the syntax of userData
     document.body.appendChild(this.dataDom);
     var exDate = new Date();
     exDate = exDate.getDate();+30;
     this.dataDom.expires = exDate.toUTCString();//Set expiration time
    }
     return false;
    }
   }
   return true;
  },
  set:function(key,value){
   if(this.isLocalStorage){
    window.localStorage.setItem(key,value);
   }
    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);
   }
    if(this.initDom()){
     this.dataDom.load(this.hname);
     return this.dataDom.getAttribute(key);
    }
   }
  },
  remove:function(key){
   if(this.isLocalStorage){
    localStorage.removeItem(key);
   }
    if(this.initDom()){
     this.dataDom.load(this.hname);
     this.dataDom.removeAttribute(key);
     this.dataDom.save(this.hname);
    }
   }
  }
}

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

The demo code involved is as follows:

<script type="text/javascript">
(function() {
  window.localData = {
    hname : location.hostname &63; location.hostname : 'localStatus',
    isLocalStorage : window.localStorage63; 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);
      }
        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);
      }
        if (this.initDom()) {
          this.dataDom.load(this.hname);
          return this.dataDom.getAttribute(key);
        }
      }
    },
    remove : function(key) {
      if (this.isLocalStorage) {
        localStorage.removeItem(key);
      }
        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 very practical technique to prevent the page from closing and to display a confirmation pop-up box when closing the page. The reference code is as follows:

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

Readers who are interested in more JavaScript-related content can check out the following special topics on this site: 'JavaScript Object-Oriented Introduction Tutorial', 'Summary of JavaScript Search Algorithm Skills', 'Summary of JavaScript Data Structure and Algorithm Skills', 'Summary of JSON Operation Skills in JavaScript', 'Summary of JavaScript Error and Debugging Skills', and 'Summary of JavaScript Mathematical Operation Usage'.

I hope this article is helpful to everyone in programming JavaScript.

Declaration: The content of this article is from the network, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please replace # with @ when reporting via email, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like