Use Cases

如何Develop Browser Extensions:Claude Code 实战指南

学习如何develop browser extensions:Claude Code 实战. 包含实用代码示例和分步指导。

浏览器扩展機能の开发を通过 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 #browser extension #Chrome extension #Manifest V3 #JavaScript