javascriptでブラウザにcookieをset、getする書き方


誰もが知っていることですが、備忘録として残します。

仕様

  • cookie setのボタンを押すとブラウザにcookieがsetされる
  • cookie getのボタンを押すとcookieの値がconsole.logに表示される

HTML

sample.html
<button class="set">cookie set</button>
<button class="get">cookie get</button>

javascript(jQuery)

sample.js
$(function() {
  $('.set').on('click', function() {
    document.cookie = 'cookieName=hogehoge';
  });

  $('.get').on('click', function() {
    console.log(GetCookie('cookieName'));
  });

  function GetCookie( name ) {
    var result = null;
    var cookieName = name + '=';
    var allcookies = document.cookie;
    var position = allcookies.indexOf( cookieName );
    if( position != -1 ) {
      var startIndex = position + cookieName.length;
      var endIndex = allcookies.indexOf( ';', startIndex );
      if( endIndex == -1 ) {
        endIndex = allcookies.length;
      }
      result = decodeURIComponent(allcookies.substring( startIndex, endIndex ));
    }
    return result;
  }
});

参考サイト