What is the shortest function for reading a cookie by name in JavaScript?

前端 未结 15 2123
猫巷女王i
猫巷女王i 2020-11-22 17:17

What is the shortest, accurate, and cross-browser compatible method for reading a cookie in JavaScript?

Very often, while building stand-alone scri

15条回答
  •  情话喂你
    2020-11-22 17:44

    (edit: posted the wrong version first.. and a non-functional one at that. Updated to current, which uses an unparam function that is much like the second example.)

    Nice idea in the first example cwolves. I built on both for a fairly compact cookie reading/writing function that works across multiple subdomains. Figured I'd share in case anyone else runs across this thread looking for that.

    (function(s){
      s.strToObj = function (x,splitter) {
        for ( var y = {},p,a = x.split (splitter),L = a.length;L;) {
          p = a[ --L].split ('=');
          y[p[0]] = p[1]
        }
        return y
      };
      s.rwCookie = function (n,v,e) {
        var d=document,
            c= s.cookies||s.strToObj(d.cookie,'; '),
            h=location.hostname,
            domain;
        if(v){
          domain = h.slice(h.lastIndexOf('.',(h.lastIndexOf('.')-1))+1);
          d.cookie = n + '=' + (c[n]=v) + (e ? '; expires=' + e : '') + '; domain=.' + domain + '; path=/'
        }
        return c[n]||c
      };
    })(some_global_namespace)
    
    • If you pass rwCookie nothing, it will get all cookies into cookie storage
    • Passed rwCookie a cookie name, it gets that cookie's value from storage
    • Passed a cookie value, it writes the cookie and places the value in storage
    • Expiration defaults to session unless you specify one

提交回复
热议问题