Back to Rules
TypeScript

Chrome Extension Development Best Practices: TypeScript, Manifest V3 & Secure Coding Guide

Claude Directory November 29, 2025
0 copies 1 downloads

Unlock expert strategies for crafting high-performance Chrome extensions with TypeScript, Manifest V3 compliance, security hardening, and optimization techniques. Includes ready-to-use code snippets for popup, background scripts, and more.

Rule Content
## Code Organization and Styling

Adopt modular TypeScript for clean, type-safe code. Favor functional approaches over classes, use meaningful names like `userPreferences` or `tabStatus`, and organize into folders: `/popup`, `/background`, `/content`, `/utils`. Always wrap operations in try-catch and log errors via `console.error`.

**Example: Modular Utility Function**
```typescript
// utils/storage.ts
export const getStoredData = async <T>(key: string): Promise<T | null> => {
  try {
    const result = await chrome.storage.sync.get(key);
    return result[key] || null;
  } catch (error) {
    console.error(`Storage read failed for ${key}:`, error);
    return null;
  }
};
```

## Core Architecture Principles

Embrace Manifest V3 by using service workers for background tasks. Separate concerns: popup for UI, content scripts for page interaction, background for persistent logic. Limit permissions to essentials like `storage`, `tabs`. Bundle with Vite or Webpack for efficient builds.

**Example: manifest.json V3**
```json
{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0",
  "permissions": ["storage", "tabs"],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  }
}
```

## Mastering Chrome APIs

Leverage `chrome.storage`, `chrome.tabs`, `chrome.runtime` with async/await. Use service workers exclusively in MV3. Schedule via `chrome.alarms`, manage icons with `chrome.action`, and detect offline states.

**Example: Background Script with Alarms**
```typescript
// background.ts
chrome.alarms.create('checkUpdates', { periodInMinutes: 30 });

chrome.alarms.onAlarm.addListener(async (alarm) => {
  if (alarm.name === 'checkUpdates') {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    // Perform update logic
  }
});
```

## Security Essentials

Enforce strict CSP in manifest, sanitize inputs to block XSS, use `chrome.runtime.sendMessage` for safe inter-script communication. Encrypt sensitive data and restrict `web_accessible_resources`.

**Example: Secure Messaging**
```typescript
// content.ts
chrome.runtime.sendMessage({ action: 'getData', payload: JSON.stringify(safeData) }, (response) => {
  if (chrome.runtime.lastError) return;
  // Handle response
});
```

## Performance Tuning

Avoid leaks by cleaning intervals/timeouts, cache API results, throttle heavy ops, and profile with DevTools. Optimize service workers to unload when idle.

**Example: Efficient Caching**
```typescript
// utils/cache.ts
const cache = new Map();

export const cachedFetch = async (url: string) => {
  if (cache.has(url)) return cache.get(url);
  const data = await fetch(url);
  cache.set(url, data);
  setTimeout(() => cache.delete(url), 5 * 60 * 1000); // 5min TTL
  return data;
};
```

## UI/UX Excellence

Design popups responsively per Material Design, add loading spinners, keyboard support (e.g., Tab/Esc), and smooth transitions.

**Example: Responsive Popup HTML**
```html
<!DOCTYPE html>
<html>
<body>
  <div id="loading" style="display: none;">Loading...</div>
  <button id="actionBtn" tabindex="0">Perform Action</button>
  <script src="popup.js"></script>
</body>
</html>
```

## Internationalization Setup

Utilize `chrome.i18n` with `_locales` folder structure. Support RTL via CSS `direction: rtl` and format dates/numbers locale-aware.

## Accessibility Features

Add ARIA roles/labels, ensure 4.5:1 contrast, screen reader compatibility, and shortcuts like Ctrl+Enter.

## Testing Strategies

Employ Jest for units, Puppeteer for e2e, test on multiple Chromium browsers, simulate errors/offline.

**Example: Jest Test**
```typescript
// storage.test.ts
test('getStoredData handles errors', async () => {
  chrome.storage.sync.get = jest.fn().mockRejectedValue(new Error('fail'));
  await expect(getStoredData('key')).resolves.toBeNull();
});
```

## Deployment and Upkeep

Craft store assets, detail privacy policy, use `chrome.runtime.onUpdateAvailable` for seamless updates, document via README.

Comments

More Rules

View all
AI/ML

GLM-4.7 Optimized Config & System Prompt Designer

Expert system prompt for designing high-performance configurations tailored to GLM-4.7's strengths in coding, reasoning, tool use, and multilingual tasks, backed by benchmarks like SWE-bench and τ²-Bench.

C
Community
AI/ML

GLM-4.7 Open-Source Coding Expert: Optimized System Prompt

Leverage GLM-4.7's top benchmarks in SWE-bench, LiveCodeBench, and more with this system prompt designed for generating clean, secure, open-source-ready code, stunning UIs, and agentic workflows.

C
Community
AI/ML

GLM-4.7 Optimized Coding Agent

This system prompt transforms an AI into GLM-4.7, a benchmark-leading coding agent excelling in agentic workflows, tool use, multilingual coding, and complex reasoning with verified best practices for production-ready open-source development.

C
Community
DevOps

Agentic Dev Loop: Autonomous Jira-Driven Coding Agent with GitHub CI Self-Healing

Ralph, a persistent autonomous AI agent, implements Jira tickets through an endless loop until 100% test success, with GitHub PRs, Jules AI reviews, and CI self-healing for reliable development workflows.

C
Claude Directory
AI/ML

Türk Hukuku Uzmanı AI Agent: Güvenilir Yasal Danışman System Prompt

Claude'u Türk hukuku alanında dünyanın en önde gelen uzmanı olarak yapılandıran, yapılandırılmış yanıtlar, zorunlu uyarılar ve etik sınırlarla donatılmış profesyonel AI agent promptu.

C
Community
Database

PostgreSQL Best Practices: Expert Subagent Guide

Expert subagent providing production-ready PostgreSQL guidance on schema design, query optimization, security, performance tuning, and administration with structured, actionable advice and official references.

C
Claude Directory