cookie、localStorage 、sessionStorage封装

cookie 存、取、删、检查

var cookie = {
  setCookie: function(key, value, expires, path, domain, secure) {
    var cookieText = "";
    expires = expires * 1000 * 60 * 60 * 24;
    var expires_date = new Date(new Date().getTime() + expires);
    cookieText += encodeURIComponent(key) + "=" + encodeURIComponent(value);
    if (expires) {
      cookieText += "; expires=" + expires_date.toGMTString();
    }
    if (path) {
      cookieText += "; path=" + path;
    }
    if (domain) {
      cookieText += "; domain=" + domain;
    }
    if (secure) {
      cookieText += "; secure";
    }
    document.cookie = cookieText;
  },
  getCookie: function(key) {
    var cookieName = encodeURIComponent(key) + "=";
    var cookieStart = document.cookie.indexOf(cookieName);
    var cookieValue = "";
    if (cookieStart > -1) {
      var cookieEnd = document.cookie.indexOf(";", cookieStart);
      if (cookieEnd == -1) {
        cookieEnd = document.cookie.length;
      }
      cookieValue = decodeURIComponent(
        document.cookie.substring(cookieStart + cookieName.length, cookieEnd)
      );
    }
    return cookieValue;
  },
  clearCookie: function(key) {
    this.setCookie(key, "", -1);
  },
  checkCookie: function(key) {
    var value = this.getCookie(key);
    if (value == "" || value == null) {
      return false;
    } else {
      return true;
    }
  }
};

localStorage && sessionStorage 存、取、删

const storage = {
setLocal: function(key, value) {
window.localStorage.setItem(key, JSON.stringify(value));
},
getLocal: function(key) {
let value = window.localStorage.getItem(key);
return JSON.parse(value);
},
setSession: function(key, value) {
window.sessionStorage.setItem(key, JSON.stringify(value));
},
getSession: function(key) {
let value = window.localStorage.getItem(key);
return JSON.parse(value);
},
clearOneLocal: function(key) {
window.localStorage.removeItem(key);
},
clearOneSession: function(key) {
window.sessionStorage.removeItem(key);
},
clearAllLocal: function() {
window.localStorage.clear();
},
clearAllSession: function() {
window.sessionStorage.clear();
}
};

你可能感兴趣的:(JS)