JS 基礎篇(十) cookie封裝

PianistK發表於2020-12-09

cookie簡單介紹

  1. cookie的特點
    1.cookie一般有大小限制為4kb,
    2.限制同一域名數量為503.讀取有域名限制
    4.時效性
    
  2. cookie 使用
    //新增cookie
    document.cookie = “key=value”; // 一次寫入一個鍵值對
    //讀取cookie 
    document.cookie //獲得所有cookie  分號分割
    
    //expires  時效
    document.cookie = `${key}=${value};${expires}=${expires}`
    //path  路徑 '/'
    document.cookie = `${key}=${value};expires=${expires};path=${path}`
    //domain  域名 'www.csdn.com'
    	document.cookie = `${key}=${value};expires=${expires};path=${path};domain=${domain}`
    

cookie 封裝


    /**
     * @description:  設定cookie
     * @param {*} key cookie 的鍵
     * @param {*} value  cookie 值
     * @param {*} expires 時間/天
     * @param {*} path 域名下路徑
     * @return {*}
     */
    function setCookie(key, value, expires, path, domain) {
      if (typeof expires === "number") {
        var date = new Date();
        date.setDate(date.getDate() + expires);
      }
      // 1.處理預設儲存的路徑
      var index = window.location.pathname.lastIndexOf("/");
      var currentPath = window.location.pathname.slice(0, index);
      path = path || currentPath;
      // 2.處理預設儲存的domain
      domain = domain || document.domain;
      document.cookie =`${key}=${value};expires=${date};path=${path};domain=${domain}`
    }

    /**
     * @description: 獲取cookie
     * @param {*} key  要獲取的cookie的鍵
     * @return {*}
     */
    function getCookie(key){
      let cookieStr = document.cookie
      console.log(cookieStr);
      cookieArray = cookieStr.split(';')
      console.log(cookieArray);
      for (let i = 0; i < cookieArray.length; i++) {
          let temp = cookieArray[i].split('=')
          if(temp[0].trim() === key){
            return temp[1]
          }
      }
      
    }
     /**
     * @description: 刪除cookie
     * @param {*} key 鍵
     * @param {*} path 路徑
     * @return {*}
     */
    function removeCookie(key,path){
      setCookie(key,1,-1,path)
    }

相關文章