【よく使う】JavaScriptでCookieを操作。取得、セット、削除する汎用的なユーティリティ

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
Cookieを操作する際にライブラリを入れるほどではなかったため
JavaScriptの汎用的なユーティリティを作成しました。
JavaScriptでcookieをセットする
ユーティリティ関数
Utills.js// expiresは日にちにしています。
export const setCookie = (name, value, expires) =>{
const date = new Date();
date.setTime( date.getTime() + 1000 * 3600 * 24 * expires );
document.cookie = `${name}=${value}; path=/; expires=${date.toUTCString()}`;
}
cookieをセットする処理
main.jsimport { setCookie } from 'Utills.js;
setCookie('Cookieの名前', ' Cookieの値', '1' );
コードの解説
日付を取得する
new Date
で現在の時刻を取得
JavaScriptconst date = new Date();
日付をセットする
1000 * 3600 * 24 *
ミリ秒と時間をかけて日単位に直しています。
JavaScriptdate.setTime( date.getTime() + 1000 * 3600 * 24 * expires );
cookieを変更
JavaScriptdocument.cookie = `${name}=${value}; path=/; expires=${date.toUTCString()}`;
JavaScriptでcookieを取得する
ユーティリティ関数
Utills.jsexport const getCookie = (name) => {
const allcookies = document.cookie;
const position = allcookies.indexOf( `${name}=` );
if( position != -1 ){
const startIndex = position + `${name}=`.length;
var endIndex = allcookies.indexOf( ';', startIndex );
if( endIndex == -1 ){
endIndex = allcookies.length;
}
return decodeURIComponent(allcookies.substring( startIndex, endIndex ) );
}
return null;
}
cookieを取得する処理
main.jsimport { getCookie } from 'Utills.js;
getCookie('Cookieの名前' );
コードの解説
cookie名があるかどうか取得
name
が含まれているかを判定
JavaScriptconst allcookies = document.cookie;
const position = allcookies.indexOf( `${name}=` );
cookie名があるかどうか判定
JavaScriptif( position != -1 ){
// 処理
}
cookieの値をパースしてデコードして返却
JavaScriptconst startIndex = position + `${name}=`.length;
var endIndex = allcookies.indexOf( ';', startIndex );
if( endIndex == -1 ){
endIndex = allcookies.length;
}
return decodeURIComponent(allcookies.substring( startIndex, endIndex ) );
cookeiを削除する
ユーティリティ関数
Utills.jsexport const deleteCookie = (name, value, expires) => {
const date = new Date('1999-12-31T23:59:59Z');
document.cookie = `${name}=; path=/; expires=${date.toUTCString()}`
}
cookieを削除する処理
main.jsimport { deleteCookie } from 'Utills.js;
deleteCookie('Cookieの名前' );
コードの解説
過去の日付をセット
JavaScriptconst date = new Date('1999-12-31T23:59:59Z');
cookieを変更
JavaScriptdocument.cookie = `${name}=; path=/; expires=${date.toUTCString()}`
- review
アジャイル初心者でも大丈夫!『アジャイルサムライ − 達人開発者への道』Jonathan Rasmusson
- review
人生が作品になる!『自分の中に毒を持て』岡本太郎
- review
体調不良の 99%が解決!『眠れなくなるほど面白い 図解 自律神経の話』小林弘幸著で学ぶ、現代人必須の自律神経コントロール術と人生を変える健康革命
- review
衝撃の事実!『睡眠こそ最強の解決策である』マシュー・ウォーカー著が明かす、99%の人が知らない睡眠の驚くべき真実と人生を変える科学的メカニズム
- review
人生が激変!『嫌われる勇気』岸見一郎・古賀史健著から学ぶ、アドラー心理学で手に入れる真の幸福と自己実現
- review
もう無駄な努力はしない!『イシューからはじめよ』安宅和人著で身につけた、99%の人が知らない本当に価値ある問題の見つけ方