LoginSignup
11
9

More than 3 years have passed since last update.

Chromeアプリ:アイコンをクリックしてアイコンの色を変える。

Last updated at Posted at 2015-01-30

勉強&メモとして書きます。
今回はchrome extensions samples の

A browser action which changes its icon when clicked

からファイルをダウンロードしたものを勉強します。これはブログタイトル通りの拡張機能です。

manifest.json

manifest.json
{
  "name": "A browser action which changes its icon when clicked",
  "description": "Change browser action color when its icon is clicked",
  "version": "1.2",
  "background": { "scripts": ["background.js"] },
  "browser_action": {
      "name": "Click to change the icon's color"
  },
  "manifest_version": 2
}

必要最低限といった感じですね。アイコンを使うのでbrowser_actionクリック時の動作をbackground.jsで記述している感じです。

background.js

background.js
var min = 1;
var max = 5;
var current = min;

function updateIcon() {
  chrome.browserAction.setIcon({path:"icon" + current + ".png"});
  current++;

  if (current > max)
    current = min;
}

chrome.browserAction.onClicked.addListener(updateIcon);
updateIcon();

きになるコードは

chrome.browserAction.setIcon({path:"icon" + current + ".png"});
chrome.browserAction.onClicked.addListener(updateIcon);

の二つですね。一つ目は名前からしてアイコンの画像を指定できるコードだと思います。
二つ目はアイコンがクリックされたら発動するコードだと思います。
最後のupdateIcon();を消したら,ファイル読み込み時に画像がない時のアイコンになっていたので,最後のupdateIcon();は読み込み時にアイコンをセットする意味があるんですね。


この機能を使ったアレンジが思いつかないので課題としておいておきます。

11
9
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
11
9