LoginSignup
43
43

More than 5 years have passed since last update.

JavaScriptでCookieを扱う

Last updated at Posted at 2013-04-10

連想配列をCookieに保存したり、Cookieを連想配列で取り出したり出来る関数

Cookieに値と有効期間を保存

JavaScript

// data・・・cookieに格納する連想配列
// period・・・cookieの有効期間(日)
var setCookie = (function(){
 return function(data, period) {
  var cookies = '';
  for (var key in data) {
   cookies += key + '=' + encodeURIComponent(data[key]) + '; ';
  }

  var expire = new Date();
  expire.setTime( expire.getTime() + 1000 * 3600 * 24 * period);
  expire.toUTCString();

  cookies += 'expires=' + expire+';';

  document.cookie = cookies;
 };
})();

Cookieから値を連想配列に変換して取得

JavaScript
var getCookie = (function(){
 return function() {
  var result = [];
  var cookies = document.cookie;

  if(cookies != ''){
   var cookieArray = cookies.split(';');
   for(var i = 0; i < cookieArray.length; i++){
    var cookie = cookieArray[i].split('=');
    result[cookie[0]] = decodeURIComponent(cookie[1]);
   }
  }
  return result;
 };
})();
43
43
1

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
43
43