【JavaScript】cookie

35 阅读2分钟

概述

  1. cookie不可跨域

  2. cookie存储在浏览器里面

  3. cookie有数量与大小的限制

    1、数量在50个左右 2、大小在4kb 左右

  4. cookie的存储时间非常灵活

  5. cookie不光可以服务器设置,客户端也可以设置

  6. 客户端 document.cookie 可以获取和写入,且只能设置一次(在 http 协议下才可以生效)。set-cookie 服务器设置。

  7. 参数 name: cookie 的名字(唯一性);value: cookie 的值; domain: cookie 在哪个域名下是有效的;path: cookie 可以有效使用的路径

document.cookie = 'name=heo; domain=localhost; path=/api';
  1. expires: cookie 的过期时间
// 到 2000.2.1 过期  取得是自己的本地时间
document.cookie = 'name=heo; expires=' + new Date(2000, 1, 1);
  1. max-age: cookie 的有效期

    1. -1:临时 cookie 不会生成
    2. 0:有效期已经到了
    3. 正数:能存活的秒数
  2. HttpOnly: 有这个标记的 cookie 前端无法操作

  3. Secure: 设置 cookie 只能通过 https 协议传输

  4. SameSite: cookie 在跨域请求的时候不能被发送

  5. 每次请求都会自动携带 cookie

封装 cookie

let manageCookie = {
    setCookie: function (name, value, date) {
        // expires 要求传入一个时间节点(默认规定传入一个天数)
        // let endDate = new Date()
        // endDate.setDate(endDate.getDate() + date)
        // document.cookie(`${name}=${value}; expires=${endDate};`)
        document.cookie = `${name}=${value}; max-age=${date};`
    },
    removeCookie: function (name) {
        this.setCookie(name, '', 0)
    },
    getCookie: function (name) {
        let cookies = document.cookie.split('; ')
        for (let i = 0; i < cookies.length; i++) {
            let item = cookies[i].split('=')
            if (item[0] === name) {
                return item[1]
            }
        }
    },
}
manageCookie.setCookie('keyyy', 'fsdafdsa', 1200)
console.log(manageCookie.getCookie('keyyy'))

应用实例

拖拽功能实现持久化。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background: pink;
            position: absolute;
            top: 100px;
            left: 100px;
        }
    </style>
</head>
<body>
<div id="box"></div>
<script>
    let manageCookie = {
        setCookie: function (name, value, date) {
            // expires 要求传入一个时间节点(默认规定传入一个天数)
            // let endDate = new Date()
            // endDate.setDate(endDate.getDate() + date)
            // document.cookie(`${name}=${value}; expires=${endDate};`)
            document.cookie = `${name}=${value}; max-age=${date};`
        },
        removeCookie: function (name) {
            this.setCookie(name, '', 0)
        },
        getCookie: function (name) {
            let cookies = document.cookie.split('; ')
            for (let i = 0; i < cookies.length; i++) {
                let item = cookies[i].split('=')
                if (item[0] === name) {
                    return item[1]
                }
            }
        },
    }

    // 拖拽
    let drag = {
        init: function (dom) {
            this.dom = dom
            this.bindEvent()
            let l = manageCookie.getCookie('newLeft')
            let t = manageCookie.getCookie('newTop')
            if (l) {
                this.dom.style.left = l + 'px'
            }
            if (t) {
                this.dom.style.top = t + 'px'
            }
        },
        bindEvent: function () {
            this.dom.onmousedown = this.mouseDown.bind(this)
        },
        mouseDown: function (e) {
            document.onmousemove = this.mouseMove.bind(this)
            document.onmouseup = this.mouseUp.bind(this)
            this.disX = e.clientX - this.dom.offsetLeft
            this.disY = e.clientY - this.dom.offsetTop
        },
        mouseMove: function (e) {
            this.newLeft = e.clientX - this.disX
            this.newTop = e.clientY - this.disY
            this.dom.style.left = this.newLeft + 'px'
            this.dom.style.top = this.newTop + 'px'
        },
        mouseUp: function () {
            document.onmousemove = null
            document.onmouseup = null
            // 鼠标抬起 存储位置信息
            manageCookie.setCookie('newLeft', this.newLeft, 1000)
            manageCookie.setCookie('newTop', this.newTop, 1000)
        },
    }
    drag.init(document.getElementById('box'))
</script>
</body>
</html>