Skip to content

拡張機能の作成方法

Chrome拡張機能を作成する手順を説明します。

ステップ1: プロジェクトの準備

Section titled “ステップ1: プロジェクトの準備”
Terminal window
my-extension/
├── manifest.json # 拡張機能の設定ファイル
├── background.js # Service Worker
├── content.js # Content Script
├── popup.html # PopupのHTML
├── popup.js # PopupのJavaScript
├── options.html # Options PageのHTML
├── options.js # Options PageのJavaScript
├── styles.css # スタイルシート
└── icons/ # アイコンファイル
├── icon16.png
├── icon48.png
└── icon128.png
{
"manifest_version": 3,
"name": "My First Extension",
"version": "1.0.0",
"description": "初めてのChrome拡張機能",
"permissions": [
"storage",
"activeTab"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_idle"
}],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
},
"options_page": "options.html"
}

ステップ2: Background Script (Service Worker)の作成

Section titled “ステップ2: Background Script (Service Worker)の作成”
background.js
// 拡張機能のインストール時に実行
chrome.runtime.onInstalled.addListener(() => {
console.log('拡張機能がインストールされました');
// 初期データの設定
chrome.storage.local.set({
count: 0
});
});
// メッセージの受信
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'INCREMENT') {
chrome.storage.local.get(['count'], (result) => {
const newCount = (result.count || 0) + 1;
chrome.storage.local.set({ count: newCount }, () => {
sendResponse({ count: newCount });
});
});
return true; // 非同期レスポンスのため
}
});
content.js
// ページ読み込み時に実行
console.log('Content Scriptが実行されました');
// ページの背景色を変更
document.body.style.backgroundColor = '#f0f0f0';
// メッセージをBackground Scriptに送信
chrome.runtime.sendMessage({ type: 'INCREMENT' }, (response) => {
console.log('カウント:', response.count);
});
popup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
width: 300px;
padding: 20px;
font-family: Arial, sans-serif;
}
button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h2>My Extension</h2>
<p>カウント: <span id="count">0</span></p>
<button id="increment">カウントを増やす</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
// カウントを表示
chrome.storage.local.get(['count'], (result) => {
document.getElementById('count').textContent = result.count || 0;
});
// ボタンクリック時の処理
document.getElementById('increment').addEventListener('click', () => {
chrome.storage.local.get(['count'], (result) => {
const newCount = (result.count || 0) + 1;
chrome.storage.local.set({ count: newCount }, () => {
document.getElementById('count').textContent = newCount;
});
});
});
options.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>拡張機能の設定</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.setting {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
}
input {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>拡張機能の設定</h1>
<div class="setting">
<label for="username">ユーザー名:</label>
<input type="text" id="username">
</div>
<div class="setting">
<label for="theme">テーマ:</label>
<select id="theme">
<option value="light">ライト</option>
<option value="dark">ダーク</option>
</select>
</div>
<button id="save">保存</button>
<script src="options.js"></script>
</body>
</html>
options.js
// 設定の読み込み
chrome.storage.sync.get(['username', 'theme'], (result) => {
document.getElementById('username').value = result.username || '';
document.getElementById('theme').value = result.theme || 'light';
});
// 設定の保存
document.getElementById('save').addEventListener('click', () => {
const username = document.getElementById('username').value;
const theme = document.getElementById('theme').value;
chrome.storage.sync.set({
username: username,
theme: theme
}, () => {
alert('設定を保存しました');
});
});

ステップ6: 拡張機能の読み込み

Section titled “ステップ6: 拡張機能の読み込み”
  1. Chromeブラウザで chrome://extensions/ を開く
  2. 右上の「デベロッパーモード」を有効にする
  3. 「パッケージ化されていない拡張機能を読み込む」をクリック
  4. プロジェクトフォルダを選択
  1. chrome://extensions/ で拡張機能の「サービスワーカー」リンクをクリック
  2. DevToolsが開き、デバッグが可能
  1. Content Scriptが注入されたページでDevToolsを開く
  2. ConsoleタブでContent Scriptのログを確認
  1. Popupを開いた状態で右クリック
  2. 「検証」を選択してDevToolsを開く
manifest.json
// ページの文字数をカウントする拡張機能
{
"manifest_version": 3,
"name": "文字数カウント",
"version": "1.0.0",
"description": "ページの文字数をカウントします",
"permissions": ["activeTab"],
"action": {
"default_popup": "popup.html"
}
}
// popup.js
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
function: () => {
const text = document.body.innerText;
return text.length;
}
}, (results) => {
document.getElementById('count').textContent = results[0].result;
});
});

Chrome拡張機能の作成手順:

  1. プロジェクトの準備: フォルダ構造とmanifest.jsonの作成
  2. Background Script: Service Workerの実装
  3. Content Script: ページに注入するスクリプトの実装
  4. Popup: 拡張機能アイコンをクリックしたときのUI
  5. Options Page: 設定ページの実装
  6. 読み込みとデバッグ: Chromeに読み込んでデバッグ

これらの手順に従うことで、基本的なChrome拡張機能を作成できます。