LoginSignup
14
10

More than 5 years have passed since last update.

[chrome拡張機能] chrome.cookies APIの使い方おぼえがき

Last updated at Posted at 2019-02-09

クッキー関係のプラグインを作りました

SUGOI!Cookies: gclid tester for Google Ads
こんな拡張機能作ってみました。

幸せになる人:
・今までgclidテストを手打ちでやってた人
・今までわざわざF12 => Application => Cookiesで
 Goolge広告やアナリティクスのクッキーを確認していた人

超ニッチです(笑)。せっかくなので、chrome.cookies APIに関してメモ。

前提

①: 公式のドキュメントはここです。

Chrome API => https://developer.chrome.com/extensions/cookies
MDN => https://developer.mozilla.org/ja/docs/Mozilla/Add-ons/WebExtensions/API/cookies

②: このAPIは、background.jsでしか呼べない。

なので、content.jsからは、
chrome.runtime.sendMessage で「このAPI呼んで!」と、
叫ぶ必要があります。例えば、下のような感じ。

content.js
/** 
 * to background.js
 */
const getCookies_ = () =>{
 chrome.runtime.sendMessage({message:'getCookies', domain:document.domain}, function callback); 
};
background.js
/**
 * eventListener 
 * chrome.cookies should be called in this file
 */
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  const domain = request.domain;
  const msg = request.message;
  if(msg=='getCookies'){
    chrome.cookies.get...
  }
  return true; // ここでtrue返してあげないと、コンソールが騒ぎます。
});

③: manifest.jsonで「このURLのクッキー触るよ」の宣言が必要

manifest.json
 {
  "permissions": [
     "cookies",
     "<all_urls>"
  ]
}

API

onChanged : クッキーに変更が加えられてた時に呼ばれます

onChanged.addEventListener

/**
 * listen to change events to cookies
 */   
chrome.cookies.onChanged.addListener((e)=>{   
  /** @type{string} 'expired', 'explicit' or 'override' */
  console.log(e.cause));   

  /** @type{Object} */
  console.log(e.cookie)); 
  const cookie = e.cookie;
    cookie.url  /** @type string*/
      // manifest.jsonで該当URLのpermissionが必要です。
    cookie.name /** @type string*/
      // クッキーは"name=val"形式。name部分です。
    cookie.value /** @type string*/
      // "name=val" のval
    cookie.domain /** @type string*/
    cookie.path /** @type string*/  
    cookie.secure /** @type boolean*/
    cookie.httpOnly /** @type boolean*/
    cookie.SameSiteStatus /** @type Enum "no_restriction", "lax", or "strict" */
    cookie.expirationDate /** @type double*/
    cookie.storeId /** @type string*/

  /** @type{boolean} if the change event has got triggered by "removing a cookie" */
  console.log(e.removed)); 
});

onChanged.removeEventListener: イベントリスナーの削除

/**
 * eventListener
 */
chrome.cookies.onChanged.addListener(doSomething_);

/**
 * remove the event added by above
 */
chrome.cookies.onChanged.removeListener(doSomething_);

/**
 * @private
 * @param {Object} event - you can access to cookie obj by "event.cookie" 
 */
function doSomething_(event){
  // do something
};

getAll : 空オブジェクトを渡せば本当に全部のクッキーが。ドメイン渡せば、そのドメインのクッキーがリターン。

chrome.cookies.getAll({},((allCookies)=>{
    doSomething_(allCookies);
}));

chrome.cookies.getAll({domain:'qiita.com'},((qiitaCookies)=>{
    doSomething_(qiitaCookies);
}));

get: url, nameを指定して、クッキーを1つゲット

chrome.cookies.get({url:'aUrl', name:'aCookieName'}, ((aCookie)=>{
    doSomething_(aCookie);
}));

remove: url, nameを指定して、クッキーを1つ削除


chrome.cookies.remove({url:'aUrl', name:'aCookieName'}, function callback);

set: クッキーを生成します。

/**
 * Objectの中にurlプロパティは必須です。
 */
chrome.cookies.set(object details, function callback);

番外編

background.jsではなく、content.jsでやりたいならdocument.cookieでやりましょう
https://developer.mozilla.org/ja/docs/Web/API/Document/cookie

//そのドメインのクッキーが、stringで入る
let cookies = document.cookie;

// Array.<string> - 'name=value'の配列 
cookies = cookies.split(';');

// 新しいクッキーを生成
document.cookie = 'aNewName=aNewVal';

以上です。最後までありがとうございました!

14
10
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
14
10