Use Cases

Claude Codeでブラウザ拡張機能を開発する方法

Claude Codeを活用してChrome拡張機能を効率的に開発。manifest.json設定からcontent script、popup UIまで実践コードで解説。

ブラウザ拡張機能の開発をClaude Codeで加速する

Chrome拡張機能の開発は、Manifest V3の仕様理解、content script、background service worker、popup UIなど多くの知識が必要です。Claude Codeならこれらを自然言語で指示するだけで生成できます。

プロジェクトの初期設定

> Chrome拡張機能のプロジェクトを作って。
> Manifest V3で、popup画面とcontent scriptを使う構成にして。
> TypeScript + Viteでビルドできるようにして。

Claude Codeが生成するmanifest.jsonの例:

{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0.0",
  "description": "Claude Codeで作ったChrome拡張機能",
  "permissions": ["storage", "activeTab"],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icons/icon16.png",
      "48": "icons/icon48.png",
      "128": "icons/icon128.png"
    }
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "css": ["content.css"]
    }
  ],
  "background": {
    "service_worker": "background.js",
    "type": "module"
  }
}

拡張アイコンをクリックしたときに表示されるポップアップです。

// popup.ts
interface Settings {
  enabled: boolean;
  highlightColor: string;
  fontSize: number;
}

const defaultSettings: Settings = {
  enabled: true,
  highlightColor: "#ffeb3b",
  fontSize: 14,
};

async function loadSettings(): Promise<Settings> {
  const result = await chrome.storage.sync.get("settings");
  return { ...defaultSettings, ...result.settings };
}

async function saveSettings(settings: Settings) {
  await chrome.storage.sync.set({ settings });
  // content scriptに設定変更を通知
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (tab.id) {
    chrome.tabs.sendMessage(tab.id, { type: "SETTINGS_UPDATED", settings });
  }
}

document.addEventListener("DOMContentLoaded", async () => {
  const settings = await loadSettings();

  const enabledCheckbox = document.getElementById("enabled") as HTMLInputElement;
  const colorInput = document.getElementById("color") as HTMLInputElement;
  const fontSizeInput = document.getElementById("fontSize") as HTMLInputElement;

  enabledCheckbox.checked = settings.enabled;
  colorInput.value = settings.highlightColor;
  fontSizeInput.value = String(settings.fontSize);

  enabledCheckbox.addEventListener("change", () => {
    settings.enabled = enabledCheckbox.checked;
    saveSettings(settings);
  });

  colorInput.addEventListener("input", () => {
    settings.highlightColor = colorInput.value;
    saveSettings(settings);
  });

  fontSizeInput.addEventListener("input", () => {
    settings.fontSize = parseInt(fontSizeInput.value);
    saveSettings(settings);
  });
});

Content Scriptの実装

Webページの内容を操作するcontent scriptです。ここではページ内テキストのハイライト機能を実装します。

// content.ts
let settings: Settings = {
  enabled: true,
  highlightColor: "#ffeb3b",
  fontSize: 14,
};

function highlightText(searchTerm: string) {
  if (!settings.enabled || !searchTerm) return;

  const walker = document.createTreeWalker(
    document.body,
    NodeFilter.SHOW_TEXT,
    null
  );

  const matches: { node: Text; index: number }[] = [];

  while (walker.nextNode()) {
    const node = walker.currentNode as Text;
    const index = node.textContent?.toLowerCase().indexOf(searchTerm.toLowerCase()) ?? -1;
    if (index !== -1) {
      matches.push({ node, index });
    }
  }

  matches.reverse().forEach(({ node, index }) => {
    const range = document.createRange();
    range.setStart(node, index);
    range.setEnd(node, index + searchTerm.length);

    const highlight = document.createElement("mark");
    highlight.style.backgroundColor = settings.highlightColor;
    highlight.className = "ext-highlight";
    range.surroundContents(highlight);
  });
}

function clearHighlights() {
  document.querySelectorAll(".ext-highlight").forEach((el) => {
    const parent = el.parentNode;
    if (parent) {
      parent.replaceChild(document.createTextNode(el.textContent || ""), el);
      parent.normalize();
    }
  });
}

// メッセージリスナー
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
  if (message.type === "HIGHLIGHT") {
    clearHighlights();
    highlightText(message.term);
    sendResponse({ success: true });
  }
  if (message.type === "SETTINGS_UPDATED") {
    settings = message.settings;
  }
});

Background Service Workerの実装

// background.ts
chrome.runtime.onInstalled.addListener(() => {
  // コンテキストメニューの追加
  chrome.contextMenus.create({
    id: "highlight-selection",
    title: "選択テキストをハイライト",
    contexts: ["selection"],
  });
});

chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  if (info.menuItemId === "highlight-selection" && tab?.id) {
    await chrome.tabs.sendMessage(tab.id, {
      type: "HIGHLIGHT",
      term: info.selectionText,
    });
  }
});

CLIツール開発との違いについてはCLIツール開発を参照してください。効率的なプロンプトの書き方は生産性を3倍にする10のTipsをご覧ください。

まとめ

Claude Codeを使えば、Manifest V3の設定からUI、content script、background workerまで、Chrome拡張機能の開発を大幅にスピードアップできます。仕様の複雑さをClaude Codeに任せて、機能のアイデアに集中しましょう。

詳しくはClaude Code公式ドキュメントを参照してください。

#Claude Code #ブラウザ拡張 #Chrome拡張 #Manifest V3 #JavaScript