Discover the best AI tools curated for professionals.

AIUnpacker
Software

Browser Extension Boilerplate AI Prompts for Web Developers

This guide provides specialized AI prompts to generate browser extension boilerplate code, helping developers bypass the initial setup friction of Manifest V3, build pipelines, and folder structures. It focuses on practical, copy-paste-ready prompts that handle the tedious configuration so you can focus on your extension's core logic.

October 6, 2025
14 min read
AIUnpacker
Verified Content
Editorial Team

Browser Extension Boilerplate AI Prompts for Web Developers

October 6, 2025 14 min read
Share Article

Get AI-Powered Summary

Let AI read and summarize this article for you in seconds.

Browser Extension Boilerplate AI Prompts for Web Developers

Browser extension development starts with boilerplate. Every extension needs a manifest, background scripts, content scripts, popup UI, and build configuration. Getting this foundation right is tedious. Getting it wrong wastes days debugging silent failures in configurations you did not understand.

The Manifest V3 migration created new boilerplate requirements that are still catching developers off guard. Service workers instead of background pages. Strict content script isolation. Host permission changes. The old boilerplates do not work, and the new ones are not well documented.

AI prompts help you generate the correct boilerplate for your specific extension architecture, handle the Manifest V3 migration path, and set up build pipelines that work with modern tooling. The goal is to get past the friction of empty editor syndrome and into the code that actually does something.

This guide provides production-ready prompts for the entire extension development setup lifecycle.

TL;DR

  • Manifest V3 is the current standard — ensure your boilerplate uses MV3 patterns; MV2 extensions face rejection from Chrome Web Store
  • Service workers replace background pages — MV3 background scripts are event-driven, not persistent; your mental model must change
  • Build pipelines prevent debugging pain — use Vite or webpack with proper extension-specific plugins from day one
  • Content script isolation is strict in MV3 — DOM access patterns differ from MV2; understand the boundaries
  • Hot reload saves development time — set up proper HMR for extension development to avoid constant reinstalls
  • Permissions should be minimal and specific — overbroad permissions cause store rejection; architect for least privilege from the start

Introduction

Browser extension development has a steeper initial curve than most web development. The boilerplate is unfamiliar, the APIs are unique, and the Manifest V3 migration introduced breaking changes that are still reverberating through the ecosystem. Many developers spend the first week of any extension project just getting the foundation to work before they write a single line of feature code.

AI prompts solve the boilerplate problem. They can generate the correct manifest structure, the appropriate background script patterns, the content script configuration, and the build pipeline setup for your specific architecture. The goal is not to replace understanding of extension development; it is to eliminate the tedious configuration work that does not require understanding to complete.

This guide is organized around the extension development lifecycle: initial setup, Manifest V3 migration, build pipeline configuration, and common development patterns. Each prompt is designed to be copy-paste-ready with your specific customization parameters.

Table of Contents

  1. Understanding Manifest V3 Architecture
  2. Generating the Manifest File
  3. Background Service Worker Setup
  4. Content Script Patterns
  5. Popup and Options Page Setup
  6. Build Pipeline Configuration
  7. Development Hot Reload Setup
  8. Common Extension Patterns
  9. Frequently Asked Questions

Understanding Manifest V3 Architecture

Manifest V3 changed the fundamental architecture of Chrome extensions. Before generating boilerplate, understand what you are building.

The MV3 architecture prompt:

Explain the Manifest V3 (MV3) architecture for Chrome extensions
and how it differs from Manifest V2.

Focus on these architectural differences:

1. BACKGROUND SCRIPTS:
   MV2: Persistent background pages with continuous execution
   MV3: Service workers that wake on events and terminate

   What this means for your extension:
   - No persistent state between invocations
   - State must be stored in chrome.storage or similar
   - Event-driven instead of polling-based
   - Lifecycle is managed by the browser

2. CONTENT SCRIPTS:
   MV2: Injected into pages with broad DOM access
   MV3: Isolated worlds with stricter boundaries

   What this means for your extension:
   - Content scripts and page scripts run in separate contexts
   - Communication via message passing required
   - Cannot directly manipulate page JavaScript objects

3. PERMISSIONS:
   MV2: Requested at install time, broad host permissions common
   MV3: Host permissions requested at runtime, graduated warnings

   What this means for your extension:
   - Design for least privilege from the start
   - activeTab permission for on-demand access
   - declarativeNetRequest instead of webRequest blocking

4. NETWORK REQUEST HANDLING:
   MV2: webRequest API with blocking
   MV3: declarativeNetRequest with declarative rules

   What this means for your extension:
   - Cannot block/modify requests dynamically
   - Must predefine rules in manifest
   - More limited but more secure

Provide the architectural implications for each of these areas.
Then identify which of these changes most commonly causes
migration problems from MV2 to MV3.

Generating the Manifest File

The manifest.json is the foundation. An incorrect manifest causes silent failures that are hard to debug.

The manifest generation prompt:

Generate a complete manifest.json for a Chrome extension with
Manifest V3 (MV3).

EXTENSION DETAILS:
Name: [EXTENSION NAME]
Version: [VERSION - e.g., "1.0.0"]
Description: [ONE SENTENCE DESCRIPTION]

PERMISSION REQUIREMENTS:
Permissions needed: [
  "storage",          // For persisting settings
  "activeTab",        // For accessing current tab on user action
  // Add others as needed: "tabs", "bookmarks", "downloads", etc.
]

HOST PERMISSIONS:
Host permission patterns: [
  // Examples:
  // "https://*.google.com/*"  // For specific domains
  // "<all_urls>"             // Only if absolutely necessary
]

EXTENSION TYPES AND FILES:
Background service worker: [FILENAME, e.g., "background.js"]
Content scripts: [
  {
    "matches": ["https://example.com/*"],
    "js": ["content-script.js"],
    "css": ["content-style.css"],
    "run_at": "document_idle"
  }
]
Popup (if needed): [POPUP HTML FILE, e.g., "popup.html"]
Options page (if needed): [OPTIONS HTML FILE, e.g., "options.html"]

FEATURES REQUIRED:
- [_] Browser action (toolbar icon with popup)
- [_] Page action (icon in address bar)
- [_] Content scripts (run on specific pages)
- [_] Background service worker
- [_] Options page (settings UI)
- [_] Omnibox (address bar keyword)
- [_] Side panel (if supporting sidePanel API)

CHROME WEB STORE ASSETS (note in manifest):
I need to include references to these icons:
- 16x16, 48x48, 128x128 PNG icons

GENERATE:
1. Complete manifest.json with all required fields for MV3 compliance
2. Identify any fields marked as deprecated in MV3
3. Note the minimum Chrome version required (currently Chrome 88+)
4. Recommend the optimal permission structure for least privilege

Include all required manifest fields and explain any optional
fields commonly used for this extension type.

Background Service Worker Setup

The background service worker is the most significant architectural change from MV2. It requires event-driven patterns.

The service worker prompt:

Generate a background service worker (background.js) for a
Manifest V3 Chrome extension.

EXTENSION PURPOSE:
[Brief description of what the extension does]

SERVICES REQUIRED (check all that apply):
- [_] Tab creation/management events
- [_] Message handling from content scripts
- [_] Browser action click handling
- [_] Storage operations (settings persistence)
- [_] Alarm/timer operations
- [_] Context menu creation
- [_] Web navigation tracking
- [_] Download operations

SERVICE WORKER PATTERN REQUIREMENTS:

1. EVENT LISTENER STRUCTURE:
   MV3 service workers must use the standard event listener pattern:

   ```javascript
   chrome.runtime.onInstalled.addListener(() => {
     // Extension install/update handler
   });

   chrome.tabs.onActivated.addListener((activeInfo) => {
     // Tab activation handler
   });

   // Add other listeners as needed
  1. STATE PERSISTENCE: Service workers terminate when idle. Cannot store state in memory. Use chrome.storage for all persistent state:

    // WRONG for MV3:
    let myState = { count: 0 };  // Lost on termination
    
    // CORRECT for MV3:
    chrome.storage.local.get(['myState'], (result) => {
      // Access stored state
    });
  2. MESSAGE PASSING: Content scripts communicate with service worker via message passing:

    // In service worker:
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      // Handle message
      if (message.type === 'GET_DATA') {
        // ... do work
        sendResponse({ data: result });
      }
      return true; // Keep message channel open for async response
    });
  3. ERROR HANDLING: Service worker failures are silent. Add comprehensive error handling:

    self.addEventListener('error', (event) => {
      console.error('Service worker error:', event.error);
      // Report to error tracking if needed
    });

Generate a complete background.js service worker that:

  1. Sets up all required event listeners
  2. Handles state persistence correctly
  3. Implements message passing for content script communication
  4. Includes proper error handling
  5. Follows MV3 best practices

Include comments explaining the MV3-specific patterns.


## Content Script Patterns

Content scripts run in an isolated world. They need different patterns than page scripts.

**The content script prompt:**

Generate a content script (content-script.js) for a Manifest V3 Chrome extension.

EXTENSION PURPOSE: [Brief description of what the content script does on pages]

TARGET PAGES: What URL patterns should this script run on? [URL patterns, e.g., “https://.example.com/”]

PRIMARY FUNCTIONALITY:

  1. [What does this script do on the page?]
  2. [What elements does it interact with?]
  3. [What data does it extract or modify?]

CONTENT SCRIPT PATTERNS FOR MV3:

  1. ISOLATED WORLD PATTERN: Content scripts run in an isolated JavaScript context. They cannot access page JavaScript variables directly:

    // CAN access:
    document.querySelectorAll('div');  // DOM elements
    window.scrollY;                     // Window properties
    
    // CANNOT access:
    // window.someGlobalVariable  // Defined by page's own JS
    // page's frameworks (jQuery, React, etc.)
  2. DOM OBSERVATION PATTERN: For dynamic pages, observe DOM changes:

    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        mutation.addedNodes.forEach((node) => {
          if (node.nodeType === Node.ELEMENT_NODE) {
            handleNewElement(node);
          }
        });
      });
    });
    
    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  3. MESSAGE PASSING TO SERVICE WORKER: Content scripts cannot communicate directly with background. Must use chrome.runtime.sendMessage:

    // Send message to service worker
    chrome.runtime.sendMessage({
      type: 'PAGE_DATA',
      payload: { url: window.location.href, title: document.title }
    }, (response) => {
      // Handle response
    });
  4. STYLING INJECTION: Inject CSS to avoid specificity conflicts:

    const style = document.createElement('style');
    style.textContent = `
      .my-extension-element {
        /* Use unique prefix to avoid conflicts */
        font-family: inherit !important;
      }
    `;
    document.head.appendChild(style);

Generate a complete content script that:

  1. Initializes correctly on page load
  2. Handles DOM content appropriately
  3. Communicates with the service worker
  4. Cleans up properly on page unload
  5. Follows MV3 content script limitations

Include documentation on what this script can and cannot access.


## Popup and Options Page Setup

Popups and options pages are standard HTML pages. They need specific patterns for extension integration.

**The popup/options page prompt:**

Generate the UI components for a Chrome extension with Manifest V3.

COMPONENT TYPE: [POPUP / OPTIONS PAGE / BOTH]

EXTENSION CONTEXT: Extension name: [NAME] What does this component do? [DESCRIPTION]

POPUP REQUIREMENTS (if applicable):

  • Simple popup with action buttons
  • Form with user inputs
  • Display of extension status/data
  • Connection to content script
  • Real-time updates

OPTIONS PAGE REQUIREMENTS (if applicable):

  • Settings form with multiple sections
  • Storage of user preferences
  • Reset to defaults functionality
  • Import/export settings
  • Help/documentation section

KEY PATTERNS FOR MV3 EXTENSION UI:

  1. POPUP SCRIPTING: Popup scripts run in their own context. Communication with service worker via chrome.runtime:

    // popup.js
    document.getElementById('myButton').addEventListener('click', async () => {
      // Get data from storage
      const data = await chrome.storage.local.get(['myKey']);
    
      // Send to content script
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      chrome.tabs.sendMessage(tab.id, {
        type: 'DO_SOMETHING',
        data: data.myKey
      });
    });
  2. OPTIONS PAGE STORAGE: Options page saves settings to chrome.storage:

    // options.js
    async function saveOptions() {
      const mySetting = document.getElementById('mySetting').value;
      await chrome.storage.local.set({ mySetting });
      // Show saved confirmation
    }
  3. OPENING OPTIONS PAGE: Users open options from extension menu. The options page URL is defined in manifest:

    // From anywhere in extension:
    chrome.runtime.openOptionsPage();

Generate:

  1. popup.html and popup.js (if popup requested)
  2. options.html and options.js (if options page requested)
  3. CSS styles appropriate for extension context
  4. Proper manifest entries for each component

Note: Extension popup height is limited (typically ~600px max). Design accordingly.


## Build Pipeline Configuration

A proper build pipeline prevents debugging pain. Set it up from the start.

**The build pipeline prompt:**

Generate a build pipeline configuration for a Chrome extension development project.

PROJECT SETUP: Package manager: [NPM / YARN / PNPM] Build tool: [VITE / WEBPACK / ROLLUP / OTHER] TypeScript: [YES / NO]

EXTENSION FILES: Source files: [PATH, e.g., ”./src”] Output directory: [PATH, e.g., ”./dist”] Manifest file: [PATH, e.g., ”./public/manifest.json”]

SPECIFIC REQUIREMENTS:

  • [_] Hot Module Replacement (HMR) for development
  • [_] TypeScript compilation
  • [_] CSS processing (PostCSS, Sass, etc.)
  • [_] Asset bundling (images, fonts, etc.)
  • [_] Environment variables
  • [_] Code splitting for content scripts
  • [_] Minification for production
  • [_] Source maps for debugging

WEBPACK CONFIGURATION FOR EXTENSIONS: Chrome extensions have specific webpack requirements:

// webpack.config.js pattern
const path = require('path');

module.exports = {
  mode: process.env.NODE_ENV,
  entry: {
    background: './src/background.js',
    popup: './src/popup.js',
    content: './src/content.js',
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
  },
  // CRITICAL: Chrome extensions cannot use HMR by default
  // Must configure specially for extension context
};

VITE CONFIGURATION FOR EXTENSIONS: Vite has excellent Chrome extension support with chrome-extension-tools:

// vite.config.js pattern
import { defineConfig } from 'vite';
import chromeExtension from 'vite-plugin-chrome-extension';

export default defineConfig({
  plugins: [chromeExtension()],
  build: {
    outDir: 'dist',
    rollupOptions: {
      input: {
        manifest: './public/manifest.json',
        popup: './public/popup.html',
        options: './public/options.html',
      },
    },
  },
});

Generate the complete build configuration for your specified setup. Include:

  1. package.json scripts section
  2. Build tool configuration file
  3. Development server setup
  4. Production build configuration
  5. Any required plugins or loaders

Specify exact package versions where known.


## Development Hot Reload Setup

Hot reload eliminates the constant reinstall cycle. Set it up properly.

**The hot reload setup prompt:**

I want to set up hot reload for Chrome extension development using [BUILD TOOL: Vite / Webpack].

DEVELOPMENT WORKFLOW PROBLEM: Without hot reload, every code change requires:

  1. Rebuild the extension
  2. Open chrome://extensions
  3. Find the extension
  4. Click reload
  5. Refresh the target page
  6. Test your change

This cycle takes 30+ seconds and destroys development flow.

HOT RELOAD SOLUTION: There are two patterns depending on your setup:

PATTERN A: Vite with chrome-extension-tools

// vite.config.js
import { defineConfig } from 'vite';
import chromeExtension from 'vite-plugin-chrome-extension';

export default defineConfig({
  plugins: [
    chromeExtension({
      // Enables auto-reload during development
      refreshOnSave: true,
    }),
  ],
});

This handles manifest, popup, options, and background reload automatically. Content scripts require page refresh.

PATTERN B: Webpack with extension-reloader

// webpack.config.js
const ExtensionReloader = require('webpack-extension-reloader');
module.exports = {
  plugins: [
    new ExtensionReloader({
      reload策略: 'manifest', // Reload on manifest change
    }),
  ],
};

FOR MY SETUP: Build tool: [VITE / WEBPACK] What needs hot reload: [BACKGROUND / POPUP / CONTENT SCRIPTS / ALL] Target Chrome version: [VERSION]

Provide:

  1. The specific configuration required
  2. Installation commands for required packages
  3. The development command to run
  4. What happens on each type of file change
  5. Limitations of this hot reload approach

Include a troubleshooting section for common hot reload issues.


## Common Extension Patterns

Common extension patterns have established solutions. Use them.

**The common patterns prompt:**

I am building a Chrome extension with Manifest V3. Generate boilerplate code for these common extension patterns.

PATTERN 1: STORAGE HELPER Common extension: Need to store and retrieve structured data

PATTERN 2: MESSAGE BROKER Common extension: Multiple scripts need to communicate through service worker

PATTERN 3: CONTEXT MENU Common extension: Right-click context menu with actions

PATTERN 4: KEYBOARD SHORTCUT Common extension: Global keyboard shortcut to trigger extension

PATTERN 5: OMNIBOX Common extension: Address bar keyword to trigger extension

PATTERN 6: TABS MANAGEMENT Common extension: Create, query, update browser tabs

PATTERN 7: NOTIFICATION Common extension: System notifications to user

PATTERN 8: DYNAMIC CONTENT SCRIPTS Common extension: Inject content script programmatically based on user action

PATTERN 9: CROSS-ORIGENT REQUEST Common extension: Make requests from content script to APIs

PATTERN 10: STORAGE SYNC Common extension: Sync settings across user’s Chrome instances

For each pattern:

  1. Show the complete, working code for the MV3 service worker
  2. Show the supporting UI or content script code if needed
  3. Note any manifest.json entries required
  4. Explain when this pattern should be used
  5. Note common mistakes with this pattern

Generate only the patterns you specified as needed. Each pattern should be copy-paste ready.


---

## Frequently Asked Questions

**How do I debug a Manifest V3 service worker?**

Service worker debugging is different from background page debugging. Open `chrome://extensions`, enable "Developer mode," find your extension, and click "service worker" link. This opens DevTools for the service worker. Use `console.log` for basic debugging. For state inspection, use `chrome.storage.local.get()` in the console to see persisted state. Remember: service workers terminate when idle, so breakpoints in idle handlers will not catch initial execution.

**How do I migrate a Manifest V2 extension to V3?**

Migration requires: replacing background pages with service workers, updating message passing to use `chrome.runtime.sendMessage` instead of `chrome.extension`, replacing `webRequest` blocking with `declarativeNetRequest`, updating permission patterns for host access, and testing all functionality in MV3 context. Use the Chrome Migration Tool as a starting point, but expect manual fixes. The hardest part is typically the background script migration because persistent state patterns must be replaced with event-driven patterns.

**Can I use React or Vue for my extension popup and options page?**

Yes, but it adds build complexity. You need a bundler that handles ES modules and produces extension-compatible output. Vite with the chrome-extension plugin handles this well. The key is ensuring the popup and options page are bundled as separate entry points with their own HTML shells. Do not expect to use client-side routing (React Router, Vue Router) in a popup; popups are single-page UI contexts. Options pages can use routing.

**What is the maximum size for a Chrome extension?**

Chrome Web Store has a 256MB size limit for uploaded packages. After compression, unpackaged size can be larger during development. Service worker scripts cannot exceed 128KB of uncompressed JavaScript before Chrome starts warning. For larger extensions, use code splitting to load features on demand. Content scripts combined cannot exceed memory limits on some devices; keep initial payload small and lazy-load features.

**How do I handle extension updates without losing user data?**

User data stored in `chrome.storage` persists across updates automatically. If you use other storage mechanisms (localStorage, IndexedDB), migration may be needed. Use the `chrome.runtime.onInstalled` event with a version check to run migration logic when users update:

```javascript
chrome.runtime.onInstalled.addListener((details) => {
  if (details.reason === 'update') {
    // Run migration from previous version
    const previousVersion = details.previousVersion;
    // Migrate data structures if needed
  }
});

This ensures user data is preserved and migrated when you ship breaking changes.

Stay ahead of the curve.

Get our latest AI insights and tutorials delivered straight to your inbox.

AIUnpacker

AIUnpacker Editorial Team

Verified

We are a collective of engineers and journalists dedicated to providing clear, unbiased analysis.

250+ Job Search & Interview Prompts

Master your job search and ace interviews with AI-powered prompts.