Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
4
Help us understand the problem. What is going on with this article?
@gigamori

【ライブラリ】超簡単(手抜き?)cookie操作用のJavascript

More than 5 years have passed since last update.

Javascriptを使ったちょっとしたトラッキング用にcookie変数を扱う関数を作った。

cookieの属性には

  • expires
  • max-age
  • domain
  • path
  • secure
  • httponly

があるが、以下の仕様で実装。

  • 有効期限はmax-ageは互換性がないので使わず、expiresで指定(日数で与える)
  • expiresを指定しない場合はセッション限定のcookieとなる
  • domainは指定しないので現在のドメイン
  • pathは指定がない場合はルート(/
  • secure, httponlyは特に指定しない

結構雑だが、最低限、実装するならこれでいいかも。
ちゃんとやりたいならjQueryとか使いましょう。

// cookieから値を取得
function getCookieValue(name){
    if (name === undefined) { throw 'argument missing!'; }
    var strResult = null;
    if (navigator.cookieEnabled && document.cookie) {
        var strParamName = name + '=';
        var strCookie = document.cookie;
        var iKeyStart = strCookie.indexOf(strParamName);
        if(iKeyStart != -1){
            var iValStart = iKeyStart + strParamName.length;
            var iValEnd = strCookie.indexOf(';', iValStart);
            if(iValEnd == -1) { iValEnd = strCookie.length; }
            strResult = '' + decodeURIComponent(strCookie.substring(iValStart, iValEnd));
        }
    }
    return strResult;
}

// cookieから値の一覧を取得
function getCookieValues(){
    var oResult = null;
    if (navigator.cookieEnabled && document.cookie) {
        var arrCookie = document.cookie.split(';');
        for (var i = 0; i < arrCookie.length; i++) {
            var arrKeyValue = arrCookie[i].split('=');
            oResult[arrKeyValue[0].replace(/^\s+|\s+$/g, '')] = arrKeyValue[1];
        }
    }
    return oResult;
}

// cookieに値をセット
function setCookieValue(name, value, iDayLife, path){
    if (name === undefined || value === undefined) { throw 'arguments missing!'; }
    path = path || '/';
    if (navigator.cookieEnabled) {
        var strCookie = name + '=' + encodeURIComponent(value);
        if(iDayLife !== undefined) {
            var d = new Date();
            d.setTime(d.getTime() + 1000 * iDayLife * 60*60*24);
            strCookie += '; expires=' + d.toUTCString();
        }
        strCookie += '; path=' + path;
        document.cookie = strCookie;
    }
}

// (GETの)URLからパラメータ取得
function getQueryValue(name){
    if (name === undefined) { throw 'argument missing!'; }
    var strResult = null;
    var strParamName = name + '=';
    if(window.location.search.length > 1){
        var strQuery = window.location.search.substring(1);
        var iPosition = strQuery.indexOf(strParamName);
        if(iPosition != -1){
            var iStart = iPosition + strParamName.length;
            var iEnd = strQuery.indexOf('&', iStart);
            if(iEnd == -1) { iEnd = strQuery.length; }
            strResult = '' + decodeURIComponent(strQuery.substring(iStart, iEnd));
        }
    }
    return strResult;
}

// パラメータのオブジェクトからGETのURLなどで使うクエリ文字列を生成
function getQueryString(oParams){
    var strQuery = '';
    for (var key in oParams){
        strQuery += key + '=' + oParams[key] + '&';
    }
    return strQuery.substr(0, Math.max(strQuery.length-1, 0));
}

cookie動作もろもろテストに使ったHTML

<html>
<head>
<script>
//
// 上記の関数群を挿入
//
(function() {
    var iPV = getCookieValue('iPV') || 0;
    iPV = parseInt(iPV) + 1;
    setCookieValue('iPV', iPV, 30);
    if (iPV > 1) {
        // 2PV目以上であればイベントを発生させてタグマネージャに送る実装やってた
        var event = document.createEvent('HTMLEvents');    
        event.initEvent('nonBounce', false, true);    
        window.dispatchEvent(event); 
    }
    alert(iPV + 'PV目です');
}());
</script>
</head>
<body>
<h2>GETのテスト</h2>
<a href="?hoge=12345">GET/hogeに12345をセット</a><br>
<a href="?fuga=09875">GET/hogeに09876をセット</a><br>
<a href="?hoge=12345&fuga=09876">GETに12345と09876をセット</a><br>
<a href="#" onclick="alert(gqv('hoge'));return false;">GET/hogeの値</a><br>
<a href="#" onclick="alert(gqv('fuga'));return false;">GET/fugaの値</a><br>

<h2>cookieのテスト</h2>
<a href="#" onclick="document.cookie='hogehoge=123';return false;">Cookie/hogehogeに123をセット</a><br>
<a href="#" onclick="document.cookie='hogehoge=';return false;">Cookie/hogehogeに空文字をセット</a><br>
<a href="#" onclick="var d=new Date();d.setTime(d.getTime()-1);document.cookie='hogehoge=; expires='+d.toUTCString();return false;">Cookie/hogehogeを消去</a><br>
<a href="#" onclick="var d=new Date();d.setTime(d.getTime()+1000*60*60*24*30);document.cookie='fugafuga=890; path=/; expires='+d.toUTCString();return false;">Cookie/fugafugaに890をセット(30日)</a><br>
<a href="#" onclick="var d=new Date();d.setTime(d.getTime()+1000*6);document.cookie='fugafuga=290; path=/; expires='+d.toUTCString();return false;">Cookie/fugafugaに290をセット(6秒)</a><br>
<a href="#" onclick="document.cookie='fugafuga=999; path=/; domain=test.com';return false;">Cookie/fugafugaに999をセット(違うドメイン)</a><br>
<a href="#" onclick="document.cookie='fugafuga=700; path=/test/';return false;">Cookie/fugafugaに700をセット(違うパス)</a><br>
<a href="#" onclick="alert(gcv('hogehoge'));return false;">Cookie/hogehogeの値</a><br>
<a href="#" onclick="alert(gcv('fugafuga'));return false;">Cookie/fugafugaの値</a><br>

</body>
</html>

Javascriptの便利なライブラリ

4
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
gigamori
広告効果測定やアクセス解析、その他データ分析が専門。WebAPIを使う開発もやっています。ここでは主に計測で使うJavascriptやデータ加工・分析、WebAPI周りの技術をまとめています。主な言語はJavascript、R、RDB(特にDWH系)、シェルスクリプト。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
4
Help us understand the problem. What is going on with this article?