cookie/localStorage/sessionStorage的区别及应用实例

261 阅读1分钟

http本身是无状态的,也就是你浏览一个网页关闭后第二次再浏览这个网页服务器不会发现是同一个人浏览的,为了弥补http无状态就出现了cookie。

  1. cookie 在我们第一次请求服务器的时候是无cookie的,服务器在收到请求以后会在http的响应里添加头部Set-Cookie,并且在Set-Cookie里进行标识在下一次请求的时候浏览器就会在http请求头部里添加Cookie,以后每一次的http请求都要把Cookie传递给服务器。
  • 使用实例:在登陆页面中的“记住我”选择框
<html>
    //html代码省略
</html>
<script>
    const username = document.querySelector('input[type="username"]')
    const checkbox = document.querySelector('input[type="checkbox"]')
    const submit = document.querySelector('input[type="submit"]')
    submit.addEventListener('click', e => {
        if (checkbox.checked && username.value !== ''){
            let key = 'username'
            let value = encodeURIComponent(username.value)
            twoDays = 2 * 24 * 60 * 60
            document.cookie = `${key}=${value}; max-age=${twoDays}`
        }
        e.preventDefault()
   })
   let arry = document.cookie.split(';').map(item => item.split('='))
   let cookie = {}
   for (let i = 0; i < arry.length; i++) {
       let name = arry[i][0]
       let value = arry[i][1]
       cookie[name] = decodeURIComponent(value)
   }
   if (document.cookie) {
       username.value = cookie.username
       checkbox.checked = true
   }
</script>
  1. localStorage localStorage会永远保存在浏览器中,可以自行删除。localStorage虽然保存下来但是不参与服务器通信web存储容量比cookie大很多,但是localStorage是同步机制会影响浏览器的渲染进度。
  • 下面使用localStorage简单模仿一下“历史搜索记录”
<html>
    //html代码省略
</html>
<script>
    const input = document.querySelector('input[type="text"])
    const button = document.querySelector('button')
    const history = document.querySelector('.history')
    if (localStorage.length > 0) {
        let key = localStorage.key[i]
        let li = document.creatElement('li')
        let liText = document.creatTextNode(localStorage.getItem(key))
        li.appendChild(liText)
        history.appendChild(li)
        //添加删除按钮
        let close = document.creatElement('span')
        li.appendChild(close)
        close.addEventListener('click', e => {
            localStorage.removeItem(key)
            li.parentNode.removeChild(li)
        })
    }
    button.addEventListener('click', e => {
        let key = new Date().valueOf()
        let value = input.value
        localStorage.setItem(key, value)
        input.value = ''
        let li = document.creatElement('li')
        let liText = document.creatTextNode(localStorage.getItem(key))
        li.appendChild(liText)
        history.appendChild(li)
        //添加删除按钮
        let close = document.creatElement('span')
        li.appendChild(close)
        close.addEventListener('click', e => {
            localStorage.removeItem(key)
            li.parentNode.removeChild(li)
        })
    })
</script>
  1. sessionStorage sessionStorage也会保存在浏览器中,只不过关闭窗口就会被删除。 sessionStorage使用方法和localStorage类似
cookie
大小4kb
兼容h4/h5
访问任何窗口
有效期可手动设置
存储位置浏览器和服务器
与请求一起发送
localStoragesessionStorage
10Mb5Mb
h5h5
任何窗口同一窗口
窗口关闭
浏览器浏览器