LoginSignup
0
0

More than 3 years have passed since last update.

JavaScriptにおけるCookieにデータを保存・参照する方法

Posted at

Cookieにデータを保存する方法

document.cookie = 'id=1';

Cookieのデータを参照する方法

alert(document.cookie);

サンプルコード

index.html
<section class="cookie">
    <h2>クッキー</h2>
    <button class="btnSave">保存する</button>
    <button class="btnRead">読み出す</button>
</section>
main.js
// 「保存する」ボタンをクリックしたとき
document.querySelector('.btnSave').addEventListener('click', () => {
    // クッキーを保存する
    document.cookie = 'id=1';
    document.cookie = 'age=30';
    document.cookie = `name=${encodeURIComponent('あいうえお')}`;
})

// 「読み出す」ボタンをクリックしたとき
document.querySelector('.btnRead').addEventListener('click', () => {
    // クッキーを読み出す
    const obj = convertCookieToObject(document.cookie);
    console.log(obj);
    //  オブジェクトを JSON 文字列に変換して表示する
    alert(JSON.stringify(obj, null, ' '))
})

/*
    クッキーをObjectに変換する。
    @param cookies クッキー文字列
    @return 連想配列
*/
function convertCookieToObject(cookies) {
    const cookieItem = cookies.split(';');
    const obj = {};
    cookieItem.forEach((item) => {
        // 「=」で分解
        const element = item.split('=');
        // キーを取得
        const key = element[0].trim();
        // バリューを取得
        const value = decodeURIComponent(element[1]);
        // 保存
        obj[key] = value;
    });
    return obj;
}
0
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
0
0