开发中少不了的Fun -- 前端本地存储

// 存储sessionStorage

  function setSessionStore (name, content) {
    if (!name) return
    if (typeof content !== 'string') {
      content = JSON.stringify(content)
    }
    window.sessionStorage.setItem(name, content)
  }

 // 获取sessionStorage

   function getSessionStore (name) {
     if (!name) return;
        var content = window.sessionStorage.getItem(name);
        if (typeof content == 'string') {
             content = JSON.parse(content)
          }
          return content;
      }


 // 删除指定sessionStore

  function removeSessionStore (name) {
    if (!name) return
    return window.sessionStorage.removeItem(name)
  }

// 删除所有sessionStore

  window.sessionStorage.clear();

// 存储localStorage

  function setStore (name, content) {
    if (!name) return
    if (typeof content !== 'string') {
      content = JSON.stringify(content)
    }
    window.localStorage.setItem(name, content)
  }

 // 获取localStorage


  function getStore (name) {
    if (!name) return
    // var value = JSON.parse(window.localStorage.getItem(name));
    var value = window.localStorage.getItem(name)
    return value
  }


// 删除localStorage

   function removeStore (name) {
    if (!name) return
    window.localStorage.removeItem(name)
  }

 // 存储cookie

  function setCookie (objName, objValue, objHours = 30) {
    var str = objName + '=' + escape(objValue)
    if (objHours != null) {
      var date = new Date()
      var ms = objHours * 3600 * 1000 * 24
      date.setTime(date.getTime() + ms)
      str += '; expires=' + date.toGMTString()
    }
    document.cookie = str
  }


// 获取cookie

   function getCookie (objName) {
    var search = objName + '='
    if (document.cookie.length > 0) {
	  var offset = document.cookie.indexOf(search)
	  if (offset != -1) {
		  offset += search.length
		  var end = document.cookie.indexOf(';', offset)
		  if (end == -1) end = document.cookie.length
		  return unescape(document.cookie.substring(offset, end))
	  } else {
		  return ''
	  }
    }
    return ''
  }

 // 删除cookie

  function delCookie (name) {
    var exp = new Date()
    exp.setTime(exp.getTime() - 1)
    var cval = getCookie(name)
    if (cval != null) {
	  document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString()
    }
  }

// 删除所有cookie

   function clearCookie () {
    var keys = document.cookie.match(/[^ =;]+(?==)/g)
    if (keys) {
	  for (var i = keys.length; i--;) {
        document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
	  }
    }
  }
原文地址:https://www.cnblogs.com/lisaShare/p/10975449.html