Chromeの機能拡張を作るときの覚書

参考

機能拡張のファイル構成

例としてchrome-extentionフォルダを作成し機能拡張に必要なファイルをその中に作る。

フォルダ内にmanifect.jsonhello.htmlを作成

chrome-extention
    ├─manifest.json
    └─hello.html

manifest.json

{
	"name": "Hello World",
	"version": "0.0.1",
	"manifest_version": 3,
	"action": {
		"default_popup": "hello.html"
	}
}

hello.html

<html>
	<body>
		<h1>Hello World!</h1>
	</body>
</html>

Chromeへ機能拡張をインストールする

アドレスバーに chrome://extentions/ と入力してにアクセスする。

デベロッパーモードをONにする。

パッケージ化されていない機能拡張を読み込むボタンでchrome-extentionフォルダを選択する。

設定ファイル等にエラーがなければ機能拡張がインストールされる。

実行イメージ

機能拡張アイコンとショートカットキーを設定する

ファイル構成

chrome-extention
    ├─hello_extention.png
    ├─manifest.json
    └─hello.html

アイコンファイルを準備

hello_extentions.png(16×16ピクセルPNG形式)

manifest.json

versionが0.0.2にアップしていることに注意!

{
	"name": "Hello World",
	"version": "0.0.2",
	"manifest_version": 3,
	"action": {
		"default_popup": "hello.html",
		"default_icon": "hello_extentions.png"
	},
	"commands": {
		"_execute_action": {
			"suggested_key": {
				"default": "Ctrl+Shift+F",
				"mac": "MacCtrl+Shift+F"
			}
		}
	}
}

😊ニコマークのアイコンクリックまたはCtrl+Shift+Fで起動する

開いているページを機能拡張から操作する

ファイル構成

chrome-extention
    ├─hello_extention.png
    ├─manifest.json
    ├─hello.html
    └─hello.js

manifest.json

{
	"name": "Hello World",
	"version": "0.0.3",
	"manifest_version": 3,
	"action": {
		"default_popup": "hello.html",
		"default_icon": "hello_extention.png"
	},
	"commands": {
		"_execute_action": {
			"suggested_key": {
				"default": "Ctrl+Shift+F",
				"mac": "MacCtrl+Shift+F"
			}
		}
	},
	"permissions": ["scripting", "tabs"],
	"host_permissions": ["http://*/*", "https://*/*"]
}

hello.html

<html lang="ja">
<head>
	<meta charset="UTF-8">
</head>
<body>
	<p>ページ操作</p>
	<p>
		<input type="button" value="背景を変える" id="change">
	</p>

	<script type="text/javascript" src="hello.js"></script>
</body>
</html>

hello.js

document.getElementById("change").addEventListener("click", () =>{
	// 開いているタブに対して操作を行う
	chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
		chrome.scripting.executeScript({
			target: { tabId: tabs[0].id },
			function: changeBackground,
		});
	});
});

function changeBackground(){
	document.body.style.backgroundColor = "lightgray";
}

イメージ

コメント