LoginSignup
6
16

More than 5 years have passed since last update.

Chrome拡張機能開発 覚書

Last updated at Posted at 2017-12-10

一から開発してみる場合

作業用のフォルダを作って次のファイルを置いて、拡張機能のページでデベロッパーモードにして、パッケージ化されていない拡張機能を読み込む...]で読込ます事で、自分用の拡張機能の開発をスタートする

manifest.json
{
    "manifest_version": 2,
    "name": "Hoge",
    "version": "0.0.0.1"
}

Google Chrome 拡張機能の開発 - 8 - (2017年12月)1年ぶりなのでもう一度はじめの一歩 - Qiita

既にあるものをいじってみる場合

以下のパスからいじってみたい拡張機能を作業用のフォルダにコピーして、拡張機能のページでデベロッパーモードにして、パッケージ化されていない拡張機能を読み込む...]で読込ます。

%UserProfile%\AppData\Local\Google\Chrome\User Data\Default\Extensions

アクションを追加する

次を追加してリロード後、アイコンをクリックすると"ほげ"が表示される。

manifest.json
    "browser_action": {
        "default_popup": "hoge.html"
    }
hoge.html
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>ほげ</title>
<style></style>
</head>
<body>
<p>ほげ</p>
</body>
</html>

バックグラウンド処理を追加する

次を追加してしてリロードすると、アラートで"ほげ"が表示される。

manifest.json
   "background": {
      "page": "bk.html"
   }
bk.html
<!doctype html>
<html>
<head>
<title>ほげ</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="bk.js"></script>
</head>
<body>
</body>
</html>
bk.js
alert("ほげ");

コンテキストメニューを追加する

次を追加・修正してリロード後、右クリックするとメニューに"ほげ"が表示される。
拡張機能の管理ページで[ビューを検証:]の欄にある"bk.html"のリンクをクリックすると、デベロッパーツールが表示される。
コンテキストメニューの"ほげ"をクリックすれば、コンソールに"ほげ"が表示される。

manifest.json
   "permissions": [ "contextMenus" ]
bk.js
chrome.contextMenus.create({title: "ほげ", id: "Hoge", contexts: ["all"], onclick: info=>{
    console.log("ほげ");
}});

コンテキストメニューの階層化

bk.jsを次のように修正。コンテキストメニューが[ほげ1].[ほげ2].[ほげ3]となる。

bk.js
chrome.contextMenus.create({title: "ほげ1", id: "Hoge1", contexts: ["all"]});

chrome.contextMenus.create({title: "ほげ2", id: "Hoge2", parentId: "Hoge1", contexts: ["all"]});

chrome.contextMenus.create({title: "ほげ3", id: "Hoge3", parentId: "Hoge2", contexts: ["all"], onclick: info=>{
    console.log("ほげ");
}});

表示中のページにスクリプトを埋め込む

次を追加してしてリロード後、任意のページを開くか再読込するとコンソールにタイトルが出力される。

manifest.json
    "content_scripts": [
        {
            "matches": [ "<all_urls>" ],
            "js" : [ "cs.js" ],
            "run_at": "document_end",
            "all_frames": true
        }
    ]

パラメーターについて
パラメーター 必須有無 説明
matches 必須 パターンを使って一致するURLでコンテンツスクリプトを有効にする。
設定例:
"matches": [ "<all_urls>" ]
js 必須 cssかjsどちらかが必須。
埋め込むスクリプトファイルを指定する
設定例:
"js": [ "jquery-3.1.1.min.js", "contentscripts.js" ]
run_at 任意 コンテンツスクリプトを実行するタイミングを指定する。
とりあえず、DOM要素を読み込んだ後のdocument_endを指定することにしておく。
設定例:
"run_at": "document_end"
all_frames 任意 対象をフレーム全てとするかの指定。
設定例:
"all_frames": true

【参考にした情報】

cs.js
window.onload = ()=>{
    console.log(document.title);
};

公開方法

Chrome Extension を作って公開する - Qiita

既に公開していれば
デベロッパー ダッシュボード - Chrome ウェブストア

6
16
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
6
16