关于cookie的使用整理

Mar 18, 2017

HTTP Cookie(也叫Web cookie或者浏览器Cookie),它保存在用户的浏览器端,并在发出符合设定条件的http请求时会默认提交的一段文本片段

document.cookie

Cookie的实现

  1. 浏览器发起http请求到Server
     GET /index HTTP/1.1
     Host: worried-k.github.io
     (...这里是省去了User-Agent,Accept等字段)
    
  2. 服务器返回HTTP Response中可以包含Cookie设置
     HTTP/1.1 200 OK
     Content-type: text/html
     Set-Cookie: token=1234
     Set-Cookie: test=webwebweb; Expires=Wed, 09 Jun 2019 14:18:14 GMT
     (...)
    
  3. 后续访问worried-k.github.io的相关页面(Expires等属性都是不可读的,也不会被请求提交)
     GET /spec.html HTTP/1.1
     Host: worried-k.github.io
     Cookie: token=1234; test=webwebweb
     (...)
     
    function setCookie(name, value, options) {
        if (value !== undefined && typeof value !== "function") {
            options = options || {};
            var seconds = -1;
            var exp = null;
            //过期时间(秒)
            if (typeof options.expires === 'number') {
                seconds = options.expires;
                exp = options.expires = new Date();
                exp.setTime(exp.getTime() + seconds * 1000);
            }

            return (document.cookie = [
                String(name), '=', window.escape(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '',
                '; max-age=' + (options["max-age"] || (options.expires ? seconds : -1)),
                options.path ? '; path=' + options.path : '; path=/',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }
    }
    function getCookie(name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        arr = document.cookie.match(reg);
        if (arr) {
            return window.unescape(arr[2]);
        } else {
            return null;
        }
    }
    function delCookie(name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = this.getCookie(name);
        if (cval !== null) {
            document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
        }
    }

会话期Cookie

持久Cookie

HttpOnly

    HTTP/1.1 200 OK
    Content-type: text/html
    Set-Cookie: token=1234
    Set-Cookie: test=webwebweb; Expires=Wed, 09 Jun 2019 14:18:14 GMT; HttpOnly
    (...)

Cookie的作用域

Cookie安全

注意