これまたよく使うのでメモ。
WebkitITPはスルー
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //read window.cookieread = function (c) { var ret = '' ; var cn = c + '=' ; var allc = document.cookie; var pos = allc.indexOf(cn); if (pos != -1) { var si = pos + cn.length; var ei = allc.indexOf( ';' , si); if (ei == -1) { ei = allc.length; } ret = decodeURIComponent(allc.substring(si, ei)); } return ret; }; //write window.cookiewrite = function (cn, val, exp, dom) { var value = cn + '=' + encodeURIComponent(val) + '; domain=' + dom + '; path=/;' ; if (exp) { var d = new Date(); d.setDate(d.getDate() + exp); var expires = d.toUTCString(); value = value + ' expires=' + expires; } document.cookie = value; }; |
使い方
1 2 3 4 5 | //クッキー名, 値, 有効日数(0ならセッション), 有効ドメイン cookiewrite( 'hoge' , 'foobar' , 30, '.kwonline.org' ); var hoge = cookieread( 'hoge' ); //foobar |
これまたES5の構文だ。