How to 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공식 문서를 참고하세요.
Related Posts
Claude Code로 리팩토링을 자동화하는 방법
Claude Code를 활용해 코드 리팩토링을 효율적으로 자동화하는 방법을 알아봅니다. 실전 프롬프트와 구체적인 리팩토링 패턴을 소개합니다.
Claude Code로 사이드 프로젝트 개발 속도를 극대화하는 방법 [예제 포함]
Claude Code를 활용해 개인 프로젝트 개발 속도를 획기적으로 높이는 방법을 알아봅니다. 실전 예제와 아이디어부터 배포까지의 워크플로를 포함합니다.
Complete CORS Configuration Guide: Claude Code 활용 가이드
complete cors configuration guide: Claude Code 활용. 실용적인 팁과 코드 예시를 포함합니다.