LoginSignup
1
0

More than 1 year has passed since last update.

自分用コードメモ - 特定のCookieを持つかどうか判別して処理をする

Last updated at Posted at 2020-02-12

よくある、特定のCookieを持つかどうかで処理を分けたいときに使うコード。例えば特定のアンケートを回答した人には同じアンケートを表示しないなどといった運用をするときに使う。

.js
function getCookieValue(cookie_name) {
    const cookies = `; ${document.cookie}`
    const values_string = cookies.split(`; ${cookie_name}=`);
    if (values_string.length > 1) return values_string.pop().split(';')[0];

}

/* 上記の修正前。filterとか正規表現を不要にした。
function getCookieValue(cookie_name){
  const cookie_name_reg = new RegExp(cookie_name+"=");
  const target_cookie = document.cookie.split(";").filter(function(c){return c.match(cookie_name_reg)});
  if(target_cookie.length != 0) return target_cookie[0].split("=")[1]
}
*/

function setCookie(cookie_name, cookie_value, days){
  if( !getCookieValue(cookie_name) ){
    doSomthing();

    const cookie_path = "path=/;"
    //有効期限の設定
    const nowdate = new Date();
    nowdate.setTime(nowdate.getTime() + days*24*60*60*1000); //日付データ
    const limit_date = nowdate.toGMTString(); //GMT形式に変換.
    const cookie_expires = "expires=" + limit_date + "; ";

    document.cookie =   cookie_name + "=" + cookie_value + ";" +
                        cookie_expires + cookie_path;
 }
}

function doSomthing(){
  console.log("doSomthing!");
}

もっと洗練された方法があれば、細かい指摘でも結構なのでコメントください!!

Qiita アカウント
Twitter アカウント

1
0
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
0