-->

2011-11-09

javascriptのsetCookieのサンプル

URLのパス名が深いほど優先順位が高いことを確認する。
jQuery Cookie pluginと見比べる。
サンプルの方にはdomain,secureの設定は無いので通常の利用はできない。

//<![CDATA[<!--
// cookieの関数をwindowオブジェクトに登録.
(function(window, undefined){
  var
  // cookieの入れ物.
  $_COOKIE = {},
  // cookieを取得する関数.
  initCookie = function(){
    var countList = {};
    document.cookie.replace(/\s*([^;=\s]*)\s*=\s*([^;=\s]*)\s*(?:$|;)/g,
                            function(){
                              if ($_COOKIE[arguments[1]] === undefined)
                              {
                                $_COOKIE[arguments[1]] = decodeURIComponent(arguments[2]);
                              }
                              if (countList[arguments[1]] === undefined)
                              {
                                countList[arguments[1]] = 0;
                              }
                              countList[arguments[1]]++;
                            });
    return countList;
  },
  // クッキーを設定する関数.
  setCookie = function(name, value, expires, path){
    expires = expires === undefined ? "Tue, 01 Jan 2030 00:00:00 GMT" : (new Date(expires * 1e3)).toGMTString();
    path = path === undefined ? "/" : path;
    document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + expires + "; path=" + path;
    $_COOKIE[name] = value;
  },
  // クッキーを削除する関数.
  unsetCookie = function(name, path){
    setCookie(name, "", 0, path);
    $_COOKIE[name] = undefined;
    delete $_COOKIE[name];
  };
  // windowオブジェクトに登録するオブジェクト名が未定義かどうか?
  if (window.initCookie === undefined && window.setCookie === undefined &&
      window.unsetCookie === undefined && window.$_COOKIE === undefined)
  {
    // $_COOKIEを初期化する.
    initCookie();
    // それぞれを登録する.
    window.initCookie = initCookie;
    window.setCookie = setCookie;
    window.unsetCookie = unsetCookie;
    window.$_COOKIE = $_COOKIE;
  }
})(window);

// firefoxでは無い場合console.log()でdocument.write()する.
(function(){
  if (typeof console != "object")
  {
    console = {};
  }
  if (1 || typeof console.log != "function")
  {
    document.write("<blockquote id=\"debug-cookie-test-001\"></blockquote>");
    $("#debug-cookie-test-001")
      .after($(document.createElement("code"))
             .css("display", "block")
             .css("white-space", "nowrap")
             .html($("#debug-cookie-test-001-script").html().replace(/\r\n?/g, "\n")
                   .replace(/[\x00-\x09\x0B-\x1F]/g, "")
                     .replace(/(?:(?:<[Bb][Rr])(?:(?:[\n]+[^<>]*)|(?:\/))?(?:>))(?:\n)?/g, "\n")
                   .replace(/([^\n])/g, function(){
                     if (arguments[1] == " ")
                     {
                       return "&nbsp;";
                     }
                     return "&#" + arguments[1].charCodeAt(0) + ";";
                   })
                   .replace(/\n/g, "<" + "br />")));
    console.log = function(str){
      $("#debug-cookie-test-001").append($(document.createElement("div"))
                                         .css("font-family", "\"MS ゴシック\",monospace")
                                         .css("line-height", "1.5em")
                                         .html(str));
      $("#debug-cookie-test-001 > div").each(function(){
        if ($(this).text().match(/^\s*\/\//))
        {
          $(this).css("background-color", "#fcc");
        }
      });
    };
  }
})();

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

// テスト.
(function(){
  var key, countList,
  dirname = location.pathname.replace(/[^\/]+$/, ""),
  test001 = function(){
    console.log("// $_COOKIEを初期化.+同じ名前で違うパス名をカウントした結果を表示.");
    countList = initCookie();
    var key = "random";
    console.log("countList[" + key + "]: " + countList[key]);
  },
  test002 = function(){
    console.log("// クッキー表示.");
    var key = "random";
    console.log("$_COOKIE[" + key + "]: " + $_COOKIE[key]);
    console.log("$.cookie(" + key + "): " + $.cookie(key));
  };

  console.log("document.cookie = " + document.cookie);
  console.log("dirname = " + dirname);

  test001();
  test002();

  console.log("// クッキーを設定.");
  value1 = Math.random();
  value2 = Math.random();
  setCookie("random", value1);
  setCookie("random", value2, undefined, dirname);
  console.log("setCookie(\"random\", " + value1 + ");");
  console.log("setCookie(\"random\", " + value2 + ", undefined, " + dirname + ");");

  test001();
  test002();

  console.log("// クッキーを削除.");
  unsetCookie("random", dirname);
  console.log("unsetCookie(\"random\", " + dirname + ");");

  return;

  test001();
  test002();

  console.log("// クッキーを削除.");
  unsetCookie("random");
  console.log("unsetCookie(\"random\");");

  test001();
  test002();
})();

//-->]]>

0 件のコメント: