【よく使う】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()}`
記事Article
もっと見る- article
React Suspenseを使う際に避けたいアンチパターン5選と解決策について紹介
- article
React SuspenseとServer Componentsの融合:クライアントとサーバの役割分担
- article
Suspense + useTransitionで滑らかなUXを実現するやり方を紹介
- article
React Suspenseでデータフェッチ!fetchでは動かない理由と正しい書き方について紹介
- article
React 18のSuspense完全対応ガイド:並列レンダリング時代の新常識
- article
Suspense × lazyで始めるコード分割:Reactアプリの初歩的最適化