cookieの設定方法
document.cookie = '[key]=[value]';
document.cookieに[key]=[value]の形の文字列を代入することでcookieにデータを設定したり、更新したりすることができる。
cookieからデータを取得する方法
let data = document.cookie;
document.cookieでアクセスすることでcookieの値を取得する事ができる。ただし、document.cookieは文字列を保持しているにすぎないので、複数の値を設定している場合は各々の[key]=[value];を連結した値が返される。
例えば、
document.cookie = 'fruit=apple'; document.cookie = 'sport=soccer'; console.log( document.cookie );
cookieに二つのkeyとvalueのセットをした後にcookieの値を取得してコンソールに出力すると、
出力:fruit=apple;sport=soccer;
という結果になる。
keyとvalueの連想配列として取得したい場合は、文字列を分割して連想配列を作る関数を別途用意してあげる必要がある。
サンプル
window.addEventListener( 'load', function( e ){
let value1 = document.querySelector( '#value1-200' );
let value2 = document.querySelector( '#value2-200' );
let cookieText = document.querySelector( '#cookie-200' );
value1.addEventListener( 'change', handleOnChangeValue1 );
function handleOnChangeValue1( e ){
document.cookie = 'key1=' + encodeURIComponent( this.value );
displayCookie();
}
value2.addEventListener( 'change', handleOnChangeValue2 );
function handleOnChangeValue2( e ){
document.cookie = 'key2=' + encodeURIComponent( this.value );
displayCookie();
}
function displayCookie(){
cookieText.innerText = decodeURIComponent( document.cookie );
}
} );
下のテキストボックスに何か入力すると、「現在のdocument.cookie」の後ろにcookieの情報が表示されます。
key1のcookieの値:
key2のcookieの値:
現在のdocument.cookie:
