---
name: chrome-extension-development
description: Chrome Extension development — Manifest V3, service workers, background scripts, popup UI, content scripts, anti-detection patterns
category: software-development
---

# Chrome Extension Development

## Overview
Develop Chrome Extensions using Manifest V3, including background service workers, popup interfaces, content scripts, and advanced patterns like anti-detection techniques.

## Core Architecture

### Manifest Version 3
```json
{
  "manifest_version": 3,
  "name": "Extension Name",
  "version": "1.0.0",
  "permissions": ["activeTab", "scripting", "storage"],
  "action": {
    "default_popup": "popup.html"
  },
  "background": {
    "service_worker": "background.js"
  }
}
```

### Key Components
- **Manifest**: Defines extension configuration, permissions, and entry points
- **Background Service Worker**: Handles background tasks, message passing, event handling
- **Popup UI**: User interface that appears when clicking extension icon
- **Content Scripts**: Inject into web pages to access and manipulate DOM
- **Action**: Defines extension icon and popup behavior

## File Structure
```
my-extension/
├── manifest.json
├── background.js
├── popup.html
├── popup.js
├── popup.css
├── content.js
└── icons/
    ├── icon16.png
    ├── icon48.png
    └── icon128.png
```

## Common Patterns

### Message Passing
Between popup and background:
```javascript
// popup.js
chrome.runtime.sendMessage({ type: 'my-action', data: value }, response => {
  if (chrome.runtime.lastError) console.error(chrome.runtime.lastError);
});

// background.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.type === 'my-action') {
    // handle action
    sendResponse({ result: 'done' });
  }
  return true; // For async response
});
```

### Tab Manipulation
```javascript
// Get active tab
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
  const tab = tabs[0];
});

// Execute script in tab
chrome.scripting.executeScript({
  target: { tabId: tab.id },
  func: myFunction,
  args: [arg1, arg2]
});
```

### Downloads
```javascript
// Trigger file download
chrome.downloads.download({
  url: URL.createObjectURL(new Blob([content], { type: 'text/markdown' })),
  filename: 'file.md',
  saveAs: true
});
```

## Anti-Detection Patterns

### Random Delays
Avoid automated detection by simulating human behavior with randomized delays.

**Implementation:**
```javascript
function randomSleep(minMs, maxMs) {
  const randomMs = Math.floor(Math.random() * (maxMs - minMs + 1)) + minMs;
  console.log(`Random delay: ${randomMs}ms (${minMs}-${maxMs}ms range)`);
  return new Promise(resolve => setTimeout(resolve, randomMs));
}
```

### Multi-Layer Delay Strategy
Implement delays at multiple points to simulate natural human behavior:

1. **Primary Delay**: After page navigation
2. **Secondary Delay**: After content extraction
3. **Inter-Action Delay**: Between operations

```javascript
// Navigate and wait
await chrome.tabs.update(tabId, { url: newUrl });
await waitForPageReady(tabId);
await randomSleep(2000, 4000); // Primary delay

// Extract content
const data = await extractData();
await randomSleep(1000, 2000); // Secondary delay
```

### Configurable Delay Modes
Allow users to adjust delay behavior based on their needs:

- **Conservative**: 3-6 seconds (safest, slowest)
- **Normal**: 2-4 seconds (recommended, balanced)
- **Aggressive**: 1-3 seconds (fastest, riskier)
- **Custom**: User-defined (1-30 seconds)

See `references/anti-detection-techniques.md` for detailed implementation.

## Development Workflow

### 1. Testing
Load unpacked extension in Chrome:
1. Navigate to `chrome://extensions/`
2. Enable Developer mode
3. Click "Load unpacked"
4. Select extension directory

### 2. Debugging
- **Popup**: Right-click extension icon → Inspect popup
- **Background**: Extension card → "service worker" link
- **Content Script**: Page elements → Inspect → Sources → Content scripts
- **Console**: Check both background and popup consoles

### 3. Permissions
Common permissions needed:
- `activeTab`: Access currently active tab
- `scripting`: Inject JavaScript/CSS
- `storage`: Store extension data
- `downloads`: Download files
- `host_permissions`: Access specific domains

## Best Practices

### Security
- Never expose API keys in client-side code
- Use `chrome.storage` for sensitive data (with user consent)
- Validate all user inputs
- Sanitize HTML content before injection

### Performance
- Minimize content script injection
- Use event listeners efficiently
- Clean up unused resources
- Cache data appropriately

### User Experience
- Provide clear feedback (status messages, progress indicators)
- Handle errors gracefully
- Support cancellation of long operations
- Maintain consistent UI/UX

## Common Pitfalls

### Manifest V3 Breaking Changes
- Background pages replaced with service workers
- `chrome.storage.sync` quota limits
- Remote code restrictions

### Content Script Context
- Content scripts run in isolated world
- Cannot access extension APIs directly
- Need message passing to communicate

### Service Worker Lifecycle
- Service workers can be terminated
- State may be lost between activations
- Use `chrome.storage` for persistence

## Support Files

### Templates
- `manifest.json` - Basic extension manifest
- `background.js` - Service worker template
- `popup.html` - Popup UI template
- `popup.js` - Popup logic template

### References
- `references/anti-detection-techniques.md` - Anti-detection patterns and random delay implementation
- `references/service-worker-patterns.md` - Background task patterns
- `references/permissions-guide.md` - Chrome permissions reference

## Related Skills
- `systematic-debugging` - Debug extension issues systematically
- `test-driven-development` - Write tests for extension functionality
- `requesting-code-review` - Review extension code before deployment
