如何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 UIの实现
扩展图标を点击したときに显示される弹出框です。
// 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官方文档。
免费 PDF:5 分钟看懂 Claude Code 速查表
只需留下邮箱,我们就会立即把这份 A4 一页速查表 PDF 发送给你。
我们会严格保护你的个人信息,绝不发送垃圾邮件。
把 Claude Code 变成真正能带来结果的工作流
先领取中文说明的免费 PDF,再进入英文商品页选择合适的教材。如果你需要团队落地、流程设计或内容变现支持,也可以直接咨询。
本文作者
Masa
深度使用 Claude Code 的工程师。运营 claudecode-lab.com——一个涵盖 10 种语言、超过 2,000 页内容的科技媒体。
相关文章
每天发布多语言 Claude Code 文章前,要先检查的 7 件事
一份实用清单,帮助你每天发布多语言 Claude Code 文章时避免漏语言、CTA 错位和线上内容未更新。
Codex Automations 是什么?让 AI 在你睡觉时完成内容运营
用 Codex Automations 自动查看流量、选择主题、写文章、改善转化路径并部署网站的实用指南。
Claude Code × GCP Cloud Functions 完全指南 | 极速开发无服务器函数
用 Claude Code 高效开发 GCP Cloud Functions。从 HTTP/Pub/Sub/Firestore 触发器实现到本地测试、部署自动化,基于 Masa 的实战经验,附完整可运行代码示例。