Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

存储

  • cookie

    • 存在本地,每次 http 请求都在 header 中带上,解决了 http 协议无状态无法判断用户身份的痛点
    • 包括一堆键值对
      • Expires 过期时间
      • Domain 来自的域名
      • Path 允许使用的路径
      • Secure 只允许 https 使用
    • 缺点
      • 容量太小,仅有 4KB
      • 不能跨域名,除非设置 Domain 为一级域名,那二级域名都能互通
    • 多标签通信案例
  • 一个标签页中 - 使用document.cookie = "key=" + value添加内容

      - 另一个页面中
          - 使用setInterval以一定时间间隔去读取cookie信息
              ```js
              setInterval(function(){
                  console.log("key=" + getCookie("key"))
              }, 5000)
              ```
              - 其中getCookie方法为document.cookie的封装
    
  • sessionStorage

    • 独立于其他选项卡和窗口,会话结束后会自动删除
  • localStorage

    • 可跨浏览器窗口和选项卡间共享,但不同浏览器的数据是不互通的

    • 持久化,会话结束后再打开仍存在,用于永久保存客户端的少量数据,每个域名可存 5MB

    • 方法

      • .setItem(key,value)
      • .getItem(key)
        • 可以直接.key 简写获取
      • .removeItem(key)
      • .clear()
        • 清空所有
      • .key(n)
        • 获取第 n 个值
    • 多标签通信案例

      • 一个标签页中

        • 使用localStorage.setItem(key,value)添加内容
        • 或者使用localStorage.removeItem(key)删除内容
      • 另一个标签页中

        • 监听 document 对象的 storage 事件,在事件的 event 对象属性中获取信息
          window.onload = function () {
            window.addEventListener("storage", function (event) {
              console.log(event.key + "=" + event.newValue);
            });
          };
          
        • event 事件对象包含以下信息:
          • domain
          • newValue
          • oldValue
          • key
  • 以上两者均与域名挂钩,不同站点之间无法互相访问

    • 子域名与根域名之间也不行!
    • http 与 https 之间也不行!
  • userdata:IE 中特有

  • globalStorage:火狐中特有