1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Cookieをオブジェクト形式で取得するJavaScriptコード

Last updated at Posted at 2017-05-17

##Cookieのリストをオブジェクト形式で取得するJSコード

document.cookie - Web API インターフェイス | MDNに載っているやり方だと、同名のCookieが複数あったときに1つの値しか取り出すことができず、不都合があったため作成。

以下のコードによりCookieを取得すれば、オブジェクトの中に配列としてCookieの値を格納しているので、同名のCookieが複数あった場合でもすべての値を取り出すことができる。

###コード

getCookieObj.js
var cookie = {
  getObj : function(){
    var cookie = document.cookie;
    var cookieObj = {};
    if(!!cookie){
      Array.prototype.forEach.call(cookie.split(';'),function(c){
       var array = [c][0].split('=').map(function(a){return a.trim()});
       var key = ~c.indexOf('=')? unescape(array[0]) : '';
       var val = ~c.indexOf('=')? unescape(array[1]) : unescape(array[0]);
       if(!cookieObj.hasOwnProperty(key)){
         cookieObj[key] = [val];
       }else{
         cookieObj[key].push(val);
       }
      });
    }
    return cookieObj;
  },
  getByName : function(name){
    var ret = [];
    var cookieObj = this.getObj();
    if(cookieObj.hasOwnProperty(name)){
      ret = cookieObj[name];
    }
    return ret;
  },
  deleteByName : function(name,path){
    var str = escape(name) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (path ? '; path=' + path : '');
    document.cookie = str;
  }
};

##実行例

image.png

1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?