LoginSignup
26
26

More than 5 years have passed since last update.

Chrome拡張の開発時にソースの更新を自動で反映させる

Last updated at Posted at 2012-12-26

特にコンテントスクリプトの開発時向けです.

注意:以下のソースを開発対象のChrome拡張に組み込んでも想定通りには動作しません.別の拡張機能として作る必要があります.

JavaScriptやCSSを少し手直しするたびに 拡張機能の管理 画面を開くのは面倒なので,「作業しているページからあるショートカット(Ctrl + a)を押すと,Chrome拡張を再読み込みし,その後ページを再読み込みする」ようなChrome拡張をつくりました.
以下,ソースです.
みそは chrome.management.setEnabled 関数ですが,chrome.managementはコンテントスクリプトからは呼べないようなので,backgroundページに処理を依頼しています.

background.js
function onMessage(request, sender, sendResponse) {
  var id = "(開発中の拡張機能のID (拡張機能の管理画面から確認))";
  chrome.management.setEnabled(id, false, function() {
    chrome.management.setEnabled(id, true, function () {sendResponse({});})
  });
  return true;
};

chrome.extension.onMessage.addListener(onMessage);
content_script.js
document.addEventListener('keydown', function (event) {
  if (event.keyCode == 65 && event.ctrlKey) { // Ctrl + a
    chrome.extension.sendMessage({}, function (response) {
      location.reload(true);
    });
  }
});
manifest.json
{
  "name": "Chawan reloader",
  "version": "0.0.1",
  "description": "To be specified",
  "background": {
    "scripts": ["background.js"]
  },
  "content_scripts": [
    {"matches" : [
        "http://b.hatena.ne.jp/my.name*" //動作させたいドメイン
      ],
      "js": ["content_script.js"],
      "run_at": "document_start"
    }
  ],
  "permissions": [
    "management"
  ]
}

追記: APIが変更になった(onRequest -> onMessageになったようなので合わせて修正しました)

--

宣伝

はてなブックマークのmyページを,軽量かつおしゃれにラップしつつ,フォルダ階層なんかも定義できるようになるChrome拡張およびFirefoxグリモンChawanを作りました(僕はメインコミッタではないですが).よろしければあわせてご覧ください.

26
26
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
26
26