はじめに
Chromeのプラグインを作成してみたいなと思い、サンプルで作ってみました!
背景色を変更する超簡単なやつです!
成果物
今回作ったファイルは下記リポジトリから取得できます。
ソースコード
ディレクトリ構成
~/develop/chrome_plugin_jisaku (main)$ tree
.
├── icon128.png
├── icon16.png
├── icon48.png
├── manifest.json
├── popup.html
└── popup.js
1 directory, 6 files
manifest.json
{
"manifest_version": 3,
"name": "Background Color Changer",
"version": "1.0",
"description": "ウェブページの背景色を変更します。",
"permissions": ["scripting", "activeTab"],
"host_permissions": ["<all_urls>"],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
}
}
}
popup.js
function changeBackgroundColor() {
document.body.style.backgroundColor = "lightblue";
}
document.addEventListener("DOMContentLoaded", () => {
const button = document.getElementById("changeColor");
if (button) {
button.addEventListener("click", () => {
console.log("ボタン押された!");
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript(
{
target: { tabId: tabs[0].id },
function: changeBackgroundColor,
},
(results) => {
if (chrome.runtime.lastError) {
console.error("実行エラー:", chrome.runtime.lastError.message);
} else {
console.log("実行結果:", results);
}
}
);
});
});
} else {
console.error("changeColor ボタンが見つかりませんでした。");
}
});
popup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>背景色変更</title>
<script src="popup.js"></script>
</head>
<body>
<button id="changeColor">背景色を変更</button>
</body>
</html>
公開手順
-
Pluginのリンクにアクセス
→chrome://extensions/ -
作成したディレクトリを設定する
これで完成です!!!めっちゃ簡単ですね!!