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

JavaScript
【よく使う】JavaScriptでCookieを操作。取得、セット、削除する汎用的なユーティリティ
Memo
この記事は公開されてから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.js
import { setCookie } from 'Utills.js; setCookie('Cookieの名前', ' Cookieの値', '1' );

コードの解説

日付を取得する

new Dateで現在の時刻を取得

JavaScript
const date = new Date();

日付をセットする

1000 * 3600 * 24 *ミリ秒と時間をかけて日単位に直しています。

JavaScript
date.setTime( date.getTime() + 1000 * 3600 * 24 * expires );

cookieを変更

JavaScript
document.cookie = `${name}=${value}; path=/; expires=${date.toUTCString()}`;

JavaScriptでcookieを取得する

ユーティリティ関数

Utills.js
export 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.js
import { getCookie } from 'Utills.js; getCookie('Cookieの名前' );

コードの解説

cookie名があるかどうか取得

nameが含まれているかを判定

JavaScript
const allcookies = document.cookie; const position = allcookies.indexOf( `${name}=` );

cookie名があるかどうか判定

JavaScript
if( position != -1 ){ // 処理 }

cookieの値をパースしてデコードして返却

JavaScript
const startIndex = position + `${name}=`.length; var endIndex = allcookies.indexOf( ';', startIndex ); if( endIndex == -1 ){ endIndex = allcookies.length; } return decodeURIComponent(allcookies.substring( startIndex, endIndex ) );

cookeiを削除する

ユーティリティ関数

Utills.js
export const deleteCookie = (name, value, expires) => { const date = new Date('1999-12-31T23:59:59Z'); document.cookie = `${name}=; path=/; expires=${date.toUTCString()}` }

cookieを削除する処理

main.js
import { deleteCookie } from 'Utills.js; deleteCookie('Cookieの名前' );

コードの解説

過去の日付をセット

JavaScript
const date = new Date('1999-12-31T23:59:59Z');

cookieを変更

JavaScript
document.cookie = `${name}=; path=/; expires=${date.toUTCString()}`

終わりに

最後までご覧いただきありがとうございます。
この記事では【よく使う】JavaScriptでCookieを操作。取得、セット、削除する汎用的なユーティリティについて紹介させていただきました。

これからも皆様の開発に役立つ情報を提供していきたいと考えています。
今後ともよろしくお願いいたします。