3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

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

仕様

  • 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;
  }
});

参考サイト

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?