よくある、特定の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!");
}
もっと洗練された方法があれば、細かい指摘でも結構なのでコメントください!!