拡張機能の作成方法
拡張機能の作成方法
Section titled “拡張機能の作成方法”Chrome拡張機能を作成する手順を説明します。
ステップ1: プロジェクトの準備
Section titled “ステップ1: プロジェクトの準備”1. フォルダ構造の作成
Section titled “1. フォルダ構造の作成”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.png2. manifest.jsonの作成
Section titled “2. manifest.jsonの作成”{ "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)の作成”// 拡張機能のインストール時に実行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; // 非同期レスポンスのため }});ステップ3: Content Scriptの作成
Section titled “ステップ3: Content Scriptの作成”// ページ読み込み時に実行console.log('Content Scriptが実行されました');
// ページの背景色を変更document.body.style.backgroundColor = '#f0f0f0';
// メッセージをBackground Scriptに送信chrome.runtime.sendMessage({ type: 'INCREMENT' }, (response) => { console.log('カウント:', response.count);});ステップ4: Popupの作成
Section titled “ステップ4: Popupの作成”<!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>// カウントを表示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; }); });});ステップ5: Options Pageの作成
Section titled “ステップ5: Options Pageの作成”<!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>// 設定の読み込み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: 拡張機能の読み込み”- Chromeブラウザで
chrome://extensions/を開く - 右上の「デベロッパーモード」を有効にする
- 「パッケージ化されていない拡張機能を読み込む」をクリック
- プロジェクトフォルダを選択
ステップ7: デバッグ
Section titled “ステップ7: デバッグ”Background Scriptのデバッグ
Section titled “Background Scriptのデバッグ”chrome://extensions/で拡張機能の「サービスワーカー」リンクをクリック- DevToolsが開き、デバッグが可能
Content Scriptのデバッグ
Section titled “Content Scriptのデバッグ”- Content Scriptが注入されたページでDevToolsを開く
- ConsoleタブでContent Scriptのログを確認
Popupのデバッグ
Section titled “Popupのデバッグ”- Popupを開いた状態で右クリック
- 「検証」を選択してDevToolsを開く
実践例: シンプルな拡張機能
Section titled “実践例: シンプルな拡張機能”// ページの文字数をカウントする拡張機能
{ "manifest_version": 3, "name": "文字数カウント", "version": "1.0.0", "description": "ページの文字数をカウントします", "permissions": ["activeTab"], "action": { "default_popup": "popup.html" }}
// popup.jschrome.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拡張機能の作成手順:
- プロジェクトの準備: フォルダ構造とmanifest.jsonの作成
- Background Script: Service Workerの実装
- Content Script: ページに注入するスクリプトの実装
- Popup: 拡張機能アイコンをクリックしたときのUI
- Options Page: 設定ページの実装
- 読み込みとデバッグ: Chromeに読み込んでデバッグ
これらの手順に従うことで、基本的なChrome拡張機能を作成できます。