Create your portfolio instantly & get job ready.

www.0portfolio.com
AIUnpacker

Best AI Prompts for Chrome Extension Development with Claude Code

AIUnpacker

AIUnpacker

Editorial Team

35 min read

TL;DR — Quick Summary

Stop wrestling with the architectural maze of Chrome extension development. This guide provides the best AI prompts for Claude Code to streamline your workflow, from managing message passing between scripts to implementing robust error handling. Learn how to leverage AI to build secure, complex extensions faster and more efficiently.

Get AI-Powered Summary

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

Quick Answer

We’ve curated the best AI prompts for Chrome extension development with Claude Code to solve architectural bottlenecks. These prompts shift the focus from writing boilerplate to strategic planning, ensuring Manifest V3 compliance and secure message passing from day one. This guide helps you build scalable extensions faster by leveraging AI as a senior architectural partner.

Benchmarks

Read Time 4 min
Tool Focus Claude Code
Target Chrome Devs
Framework Manifest V3
Focus Architecture & Security

Revolutionizing Extension Development with AI

Why do so many promising Chrome extensions die in development? The culprit is almost always the same: the architectural maze. You’re not just writing a single script; you’re orchestrating a conversation between a popup, a background service worker, and content scripts injected into web pages. This is where things get tricky. A single misstep in message passing can lead to silent failures, and a lapse in security best practices can expose your users to risk. The traditional process is often a frustrating cycle of boilerplate, debugging, and wrestling with the Chrome API’s unique quirks.

But what if you could architect this complex system with the clarity of a senior developer, right from the start? This is where AI-assisted coding with tools like Claude Code fundamentally changes the game. Instead of getting bogged down in the syntax of chrome.runtime.sendMessage, you can describe the desired data flow and security constraints in natural language. The AI acts as an expert partner, generating robust boilerplate, implementing intricate logic, and enforcing Manifest V3 security patterns that are easy to miss. It’s about shifting your focus from how to code the basics to what you want to build.

This guide is your curated, battle-tested library of AI prompts designed specifically for Chrome extension development. We move beyond simple code generation and into strategic implementation. You’ll discover prompts that help you plan the entire extension architecture upfront, ensuring the message passing between your popup and background script is not just functional, but secure and resilient. This is about building smarter, more secure, and more efficiently than ever before.

Section 1: The Foundation - Architectural Planning Prompts

Ever spent a week building a Chrome extension only to realize the popup can’t reliably talk to the background script, or your manifest.json is a tangled mess of permissions? This is the most common point of failure, and it’s where AI can be your most valuable architect, not just a code generator. Before you write a single line of logic, you need a blueprint. These prompts are designed to force Claude Code to think like a seasoned extension developer, planning for scale, security, and Manifest V3 compliance from the very first line.

Prompt 1: The Master Architect Blueprint

A scalable extension is built on a modular foundation, not as a single, monolithic script. The goal here is to establish clear communication channels and responsibilities between the different parts of your extension before you start coding. This prompt generates a complete architectural plan, defining the data flow and file structure.

The Prompt:

Act as a senior Chrome extension developer. Create a comprehensive architectural blueprint for a new extension that [describe your extension's core function, e.g., "summarizes articles on any page and saves the summary to a user account"]. 

Your blueprint must include:
1.  **File Structure:** A tree-view of the necessary folders and files (e.g., `src/`, `dist/`, `background.js`, `content.js`, `popup/`, `options/`).
2.  **Component Roles:** A clear description of the responsibility for each key component:
    *   `manifest.json`: The central configuration hub.
    *   Background Service Worker (`background.js`): The long-running logic handler for API calls and state management.
    *   Content Scripts (`content.js`): The DOM interaction layer.
    *   Popup (`popup.html`, `popup.js`): The user-facing interface for immediate actions.
    *   Options Page (`options.html`, `options.js`): The user-facing interface for configuration.
3.  **Data Flow Diagram (in text):** Describe the message passing sequence for the primary user action. For example, detail how a user clicking a "Summarize" button in the popup leads to a message being sent to the background script, which then instructs the content script to extract text, and how the result is returned and displayed.
4.  **Security Considerations:** Highlight any potential security risks in this architecture (e.g., sanitizing user input from the DOM) and how to mitigate them.

Ensure the architecture is modular, scalable, and adheres to Manifest V3 best practices.

Why this works:

  • Forces Holistic Thinking: It prevents you from jumping straight into code. By defining the data flow first, you avoid the common pitfall of creating tightly coupled components that are impossible to debug.
  • Establishes a Contract: The “Data Flow Diagram” acts as a contract between components. This is a professional practice that ensures you understand how information will move through your system, reducing integration errors later.
  • Builds a Searchable Foundation: The output is a text-based document you can save in your project’s README.md. This becomes a reference for you and any collaborators, ensuring everyone understands the “why” behind the architecture.

Prompt 2: Manifest V3 Compliance and Optimization

Manifest V3 isn’t just a checklist; it’s a fundamental security and performance shift. A common mistake is over-requesting permissions or misconfiguring the Content Security Policy (CSP), which can get your extension rejected from the Chrome Web Store. This prompt acts as a security guard, ensuring your extension’s foundation is compliant from day one.

The Prompt:

Generate a complete `manifest.json` file for my Chrome extension based on the following requirements:

*   **Name:** "Article Summarizer Pro"
*   **Version:** "1.0.0"
*   **Description:** "Highlights key points on any article page and saves them to the cloud."
*   **Host Permissions:** Only request access to the specific sites needed (e.g., `https://*/*` for article reading, but explain the security implications of this broad permission and suggest a more restrictive alternative if possible).
*   **Permissions:** Required permissions for `storage` (to save user settings) and `contextMenus` (to add a right-click action).
*   **Background:** Use Manifest V3's `service_worker` and specify the correct script path.
*   **Action:** Define the popup HTML file.
*   **Options:** Define the options page HTML file.
*   **Content Scripts:** Define a content script that injects on all HTTP/HTTPS pages, but with a strict `js` array and `css` array.
*   **CSP:** Provide a secure default Content Security Policy for the extension, especially for any inline scripts or styles.

Critique your own generated manifest. After providing the JSON, list 3 potential security or policy violations a developer might commonly make with this configuration and how to avoid them.

Why this works:

  • Proactive Error Prevention: The critique section is a “golden nugget.” It forces the AI to act as a reviewer, pointing out common mistakes like using unsafe-eval or not understanding the difference between host_permissions and permissions. This is an insider tip that saves you from a rejection.
  • Context-Awareness: By asking it to explain the implications of broad permissions, you’re training the AI to think like a security-conscious developer, not just a syntax engine. It helps you make informed decisions about what your extension actually needs to function.

Prompt 3: Dependency and Build System Setup

Manually managing extension files is a recipe for disaster. A professional workflow requires a build system like Webpack or Vite to bundle your code, manage dependencies with npm, and create an optimized dist folder for deployment. This prompt sets up that entire pipeline for you.

The Prompt:

I am setting up a professional development environment for a Chrome Extension using [choose one: Webpack or Vite]. My project uses npm for package management.

Please generate all the necessary configuration files and a `package.json` script section to achieve the following:
1.  **Development Workflow:** A `dev` script that bundles my source code from a `src/` directory into a `dist/` directory. It should also include a `web-ext` command to run the extension in a temporary browser profile with live reloading.
2.  **Production Build:** A `build` script that creates an optimized, minified production build in the `dist/` directory, ready for zipping and submission to the Chrome Web Store.
3.  **File Structure:** Show the `package.json` dependencies and scripts, the full `webpack.config.js` (or `vite.config.js`), and a sample `tsconfig.json` if using TypeScript.
4.  **Environment Variables:** Explain how to handle environment variables (e.g., for API keys) securely, ensuring they are not bundled into the client-side code. Provide a simple example using a `.env` file.

Focus on a clean, modern setup that separates source from distribution and automates the tedious parts of development.

Why this works:

  • Automates the Hardest Part: Setting up a build system from scratch is often the biggest hurdle for developers new to extensions. This prompt gets you a working, professional setup in seconds, not hours.
  • Focuses on Developer Experience: By specifically asking for live reloading (web-ext), you’re prioritizing a fast feedback loop, which is critical for productivity. This is a detail that separates a basic setup from a truly efficient one.
  • Addresses a Critical Security Gap: The prompt’s specific request for handling environment variables teaches you the correct, secure pattern from the start. Many developers accidentally leak API keys by hardcoding them; this prompt builds the right security practice into your workflow by design.

Section 2: Mastering Message Passing and Secure Communication

Message passing is the central nervous system of any Chrome extension. It’s how your popup talks to your background service worker, how your content script requests data, and how you maintain a secure, sandboxed environment. Getting this wrong doesn’t just lead to bugs; it opens security holes that can expose user data. The core challenge is that these components live in isolated worlds, and the bridge you build between them must be both robust and secure.

In my experience building extensions that handle sensitive user information, the most common failure point is a naive message-passing implementation. Developers often forget to validate the message sender or assume a message structure, leading to crashes or, worse, injection vulnerabilities. The prompts below are designed to enforce a security-first mindset, ensuring your communication channels are airtight from day one.

Prompt 4: Secure Popup-to-Background Script Handshake

This prompt is your first line of defense. It forces the AI to generate code that doesn’t just pass messages, but actively inspects them. It validates where a message came from and what it contains before any logic is executed. This pattern is non-negotiable for any extension that handles authentication tokens, user preferences, or interacts with external APIs.

The Prompt:

Generate the JavaScript code for a secure message-passing system between a Chrome extension's popup and its background service worker.

**Requirements:**
1.  **Popup Script (`popup.js`):** Use `chrome.runtime.sendMessage` to send a message with a specific structure: `{ type: 'FETCH_USER_DATA', payload: { userId: 'user123' } }`. Include error handling for when the background script is unreachable.
2.  **Background Script (`background.js`):** Implement a `chrome.runtime.onMessage` listener that performs the following security checks:
    *   **Origin Validation:** Check that `sender.id` matches `chrome.runtime.id` to ensure the message is from your own extension and not a malicious webpage.
    *   **Schema Validation:** Verify that the message object has a `type` property and that it matches an allowed list (e.g., 'FETCH_USER_DATA'). Reject any messages without a valid type.
    *   **Data Sanitization:** Before processing the `payload`, ensure it's a plain object and doesn't contain any executable code or unexpected properties.
3.  **Response:** The background script should process the valid request and send back a structured response, for example: `{ status: 'success', data: { ... } }`. If any validation fails, it should respond with a clear error: `{ status: 'error', message: 'Invalid request' }` and `console.warn` the suspicious message for debugging.
4.  **No Hardcoded Secrets:** Do not include any API keys or secrets in the generated code. Assume these will be handled via `chrome.storage` or environment variables.

Why this prompt works:

  • Enforces a Security Contract: By explicitly defining the message structure (type, payload), you create a strict contract. The generated code will reject any malformed messages, preventing a whole class of bugs.
  • Prevents Extension Hijacking: The sender.id check is a critical “golden nugget” of security. It stops a malicious website from sending a message to your extension’s background script and tricking it into performing actions on the user’s behalf.
  • Promotes Defensive Programming: The request for schema validation and data sanitization forces the AI to generate code that anticipates bad input. This is a hallmark of expert-level development and saves you from future security audits.

Prompt 5: Content Script Isolation and Injection

Content scripts run in the context of the webpage, which is a hostile environment. The page’s own JavaScript can overwrite your variables, and your script can conflict with theirs. The solution is to use window.postMessage to create a secure, one-way communication channel from your content script to the page, while keeping your actual logic completely isolated.

The Prompt:

Create a robust content script for a Chrome extension that needs to safely communicate with a webpage's own JavaScript.

**Specifications:**
1.  **Isolation:** The script must be fully self-contained. It should not pollute the global `window` object with any variables or functions. Use an IIFE (Immediately Invoked Function Expression) to create a private scope.
2.  **Safe Injection:** The script needs to detect a specific element on the page (e.g., a `div` with `id="app-container"`) and inject a small UI component (a button) into it. It must handle cases where the target element doesn't exist yet, perhaps due to a Single-Page App (SPA) navigation.
3.  **Secure Communication:** When the injected button is clicked, the content script must send a message *to the webpage* using `window.postMessage`. The message must be a custom object, for example: `{ source: 'my-extension', type: 'BUTTON_CLICKED', data: { timestamp: Date.now() } }`.
4.  **Event Listening:** The script should also listen for messages *from the webpage* (again, checking `event.source === window` and `event.data.source === 'my-extension'`) to receive data back. This creates a two-way bridge without direct function calls.
5.  **Conflict Avoidance:** The script should be idempotent. If it runs multiple times on the same page (e.g., due to an SPA re-render), it should not re-inject the button or create duplicate event listeners.

Why this prompt works:

  • Solves the SPA Problem: By explicitly asking for handling missing elements and re-injection logic, the prompt guides the AI to generate code that works on modern web applications, not just static pages.
  • Respects the Sandbox: The focus on window.postMessage instead of direct function calls is key. It acknowledges the security boundary between the content script and the page, a fundamental concept that prevents your extension from being a vector for cross-site scripting (XSS) attacks.
  • Enforces Clean Code: The demand for an IIFE and no global pollution is a best practice that prevents subtle bugs where your extension’s variables clash with the page’s. This is a detail that separates professional code from a quick-and-dirty script.

Prompt 6: One-Time vs. Persistent Connections

Choosing the right communication channel is about performance and architecture. chrome.runtime.sendMessage is perfect for a single request-response cycle. But if you need a long-lived, continuous connection—like streaming logs from a background process or maintaining a real-time state—the overhead of sendMessage is inefficient. That’s where chrome.runtime.connect shines.

The Prompt:

Generate a complete, production-ready example demonstrating the difference between `chrome.runtime.sendMessage` and `chrome.runtime.connect` in a Chrome extension.

**Part 1: One-Time Request (`sendMessage`)**
*   Create a `popup.js` that uses `chrome.runtime.sendMessage` to request a single, static piece of data (e.g., a user's saved theme preference).
*   Create a `background.js` listener for this message that fetches the data from `chrome.storage.sync` and sends it back once.

**Part 2: Persistent Connection (`connect`)**
*   In the same `popup.js`, create a function that establishes a long-lived port using `chrome.runtime.connect({ name: 'status-port' })`.
*   The background script must listen for this connection via `chrome.runtime.onConnect`.
*   Once connected, the background script should simulate a long-running task by sending a series of messages over the port (e.g., 'Processing...', '50% complete', 'Done!') every 2 seconds.
*   The `popup.js` must listen for these messages on the port's `onMessage` event and also handle the `onDisconnect` event gracefully, cleaning up listeners.

**Part 3: Lifecycle Management**
*   Include code in the popup to explicitly close the port (`port.disconnect()`) when the user closes the popup window to prevent dangling connections and memory leaks.
*   Add error handling for cases where the background script is not available when `connect` is called.

Why this prompt works:

  • Provides a Direct Comparison: By asking for both patterns in a single, cohesive example, the prompt helps you understand the trade-offs. You can see exactly when to use each method, which is far more effective than reading two separate documentation pages.
  • Focuses on the Full Lifecycle: The request for onDisconnect handling and explicit port.disconnect() calls is an expert-level instruction. It teaches the developer to manage resources properly, a common source of memory leaks in extensions that developers often overlook.
  • Addresses Real-World Scenarios: The “long-running task” simulation is a perfect use case for connect. It demonstrates a tangible problem that sendMessage would solve poorly, giving the developer a clear mental model for when to reach for a persistent connection.

Section 3: UI/UX Design and Frontend Implementation

You’ve built the backend logic, but what does the user actually see? A powerful extension with a clunky, unresponsive UI is dead on arrival. The browser’s popup window is a unique environment: it has a fixed, narrow width, it disappears the moment it loses focus, and it must be built for speed. Getting the frontend right is about more than just aesthetics; it’s about creating a seamless, intuitive experience that feels like a native part of the browser itself.

This section provides the prompts to transform your extension from a collection of scripts into a polished, professional product. We’ll cover generating a modern popup, building a robust options page for user configuration, and extending your reach into the page with interactive context menus and side panels.

Prompt 7: Generating a Modern Popup Interface

The Chrome popup is a constrained canvas. It demands a design that is both visually appealing and information-dense, all within a few hundred pixels. A common mistake is overloading it with content, leading to a frustrating scroll-fest. The goal is clarity and immediate utility.

Here is a prompt designed to generate a professional, responsive popup using modern vanilla CSS (to avoid the complexity of a build step for a simple UI) while respecting Chrome’s unique constraints.

Generate a complete, self-contained `popup.html` and `popup.css` for a Chrome Extension (Manifest V3). The design must be modern, responsive, and fit within a narrow (approx. 350px wide) popup window.

**Requirements:**
1.  **Layout:** Use a clean, single-column layout with a header (logo + title), a main content area for user controls, and a footer for status or actions.
2.  **Styling:** Use a modern, dark-themed color palette that's easy on the eyes. Implement CSS variables for easy theming. Use Flexbox or Grid for layout.
3.  **Functionality:** Include a placeholder `<button>` to demonstrate an action. Add a small status `<div>` that is initially hidden, meant to show success or error messages.
4.  **Chrome Constraint Awareness:** Ensure all text is legible, buttons are large enough to be easily clickable, and there is no horizontal overflow. The design should not require horizontal scrolling under any circumstances.
5.  **JavaScript:** Include a minimal `popup.js` script that adds a click event listener to the button. When clicked, it should send a message to the background script using `chrome.runtime.sendMessage` and briefly show the status div with a "Processing..." message.

Why this prompt works:

  • Specificity Breeds Quality: By explicitly stating the “narrow” width and forbidding horizontal scrolling, you force the AI to design for the actual environment, not a generic web page. This is a crucial detail that prevents common UI bugs.
  • Focus on User Experience: The request for a “status <div>” that can show feedback is a golden nugget. Users need to know if an action succeeded or failed. This prompt builds that essential UX pattern directly into the template.
  • Practical Integration: The popup.js requirement ties the UI directly to the extension’s core messaging system, providing a complete, runnable example instead of just a static design. It demonstrates the full user-to-backend flow.

Prompt 8: Dynamic Options Page Generation

The options page is where your extension gains its power and personality. Users need to configure settings, connect accounts, and customize behavior. This page lives in a standard browser tab, giving you more space, but it must reliably save and retrieve settings using chrome.storage.sync. Trust is paramount here; users need to know their settings won’t vanish.

This prompt guides the AI to create a comprehensive and secure options page.

Create a full-featured `options.html` page for my Chrome Extension, along with its corresponding `options.js` logic.

**Design and UI Requirements:**
1.  **Layout:** A clean, centered form layout. Use a `<form>` element for semantic correctness.
2.  **Controls:** Include a mix of input types: a text input for an "API Key," a checkbox for "Enable Notifications," and a select dropdown for "Theme Preference" (Light, Dark, Auto).
3.  **Feedback:** Add a `<span>` or `<div>` to display a "Settings Saved" message upon successful save.

**JavaScript Logic Requirements:**
1.  **Loading Settings:** On page load (`DOMContentLoaded`), the script must retrieve the current settings from `chrome.storage.sync` and populate the form fields with these values.
2.  **Saving Settings:** Add an event listener to the form's `submit` event. It must prevent the default form submission.
3.  **Security:** The script must validate the API key input. Do not allow the user to save an empty key. Add a comment explaining why this is important.
4.  **Storage:** Use `chrome.storage.sync.set` to save the form's values. After saving, display the "Settings Saved" message for 2 seconds, then hide it.
5.  **Error Handling:** If `chrome.storage.sync` fails for any reason, log the error to the console and display a user-friendly error message.

Why this prompt works:

  • Enforces Best Practices: The prompt explicitly asks for the DOMContentLoaded event listener, which is the correct way to initialize an options page. It also demands the use of a <form> element for better accessibility and semantics.
  • Builds Security-Conscious Habits: By including the “Security” requirement and asking for a comment explaining its importance, the prompt teaches why validation is critical. It’s not just about data integrity; it’s about preventing users from making mistakes that could lead to API failures or security risks.
  • Handles the Full Data Lifecycle: It covers both reading from and writing to chrome.storage.sync, providing a complete, end-to-end solution for state management in an options page. The request for error handling makes the generated code production-ready.

Prompt 9: Interactive Context Menus and Side Panels

To make your extension truly powerful, you need to meet users where they are: right-clicking on a page. Context menus provide direct, context-aware actions. Similarly, the newer Side Panel API offers a persistent, always-on interface without obstructing the user’s view.

This prompt focuses on the programmatic creation and management of these UI elements, including the critical logic for communication.

Write the complete background service worker code to manage interactive context menus and the Chrome Side Panel.

**Context Menu Logic:**
1.  **Creation:** On `chrome.runtime.onInstalled`, create three context menu items:
    *   An item that appears when you highlight text, labeled "Analyze Selection".
    *   An item that appears on all images, labeled "Process Image".
    *   A general item that appears on the page, labeled "Open Extension Tools".
2.  **Interaction:** Add a `chrome.contextMenus.onClicked` listener. For the "Analyze Selection" item, pass the selected text (`info.selectionText`) to a content script on the active tab. For the "Process Image" item, pass the source URL (`info.srcUrl`).
3.  **Security:** Ensure all message passing uses a structured object and does not rely on simple strings.

**Side Panel Logic:**
1.  **Opening:** Add a listener for a browser action (toolbar icon) click. When clicked, it should open the side panel by setting `chrome.sidePanel.setOptions` with the URL `sidepanel.html`.
2.  **Configuration:** Ensure the side panel is enabled for all windows using `chrome.sidePanel.setOptions` with `{ enabled: true }`.
3.  **Communication:** Briefly describe in a comment how the side panel's content script would receive the data passed from the context menu click (e.g., via `chrome.runtime.onMessage`).

Why this prompt works:

  • Prevents Common Bugs: The first instruction to place chrome.contextMenus.create inside chrome.runtime.onInstalled is a critical “golden nugget.” This is the single most common mistake developers make, which leads to duplicate menu items on every extension reload. This prompt builds the correct pattern by default.
  • Promotes Robust Communication: The security requirement to use structured objects for messages instead of raw strings is an expert-level tip. It prevents brittle code that breaks if the message format changes and makes the data flow predictable and easy to debug.
  • Modern API Coverage: By combining context menus with the Side Panel API, the prompt provides a modern, forward-looking solution. It addresses two distinct but complementary ways of extending the browser UI, giving the developer a versatile toolkit for user interaction. The explicit request for a comment on the communication flow ensures the developer understands how these disparate parts connect.

Section 4: Advanced Functionality and API Integration

Once you’ve mastered the core architecture and communication channels, your extension can truly become a powerful productivity tool. How do you handle complex browser state, securely connect to external services, and perform heavy tasks without bogging down the user’s browser? These are the challenges that separate basic extensions from professional, indispensable tools. This section provides the exact prompts to unlock these advanced capabilities, ensuring you can manage user sessions, integrate with APIs securely, and offload intensive work—all while adhering to the strict security model of Manifest V3.

Prompt 10: Tab and Window Management Logic

Productivity extensions thrive on their ability to orchestrate the user’s browsing environment. Whether you’re building a session manager, a tab suspender, or a workspace organizer, you need to query, create, and manipulate browser tabs and windows with precision. A naive approach can lead to race conditions or performance issues, but a well-structured prompt can generate robust, event-driven logic.

This prompt is designed to generate a comprehensive background.js module for managing tab and window operations. It explicitly asks for error handling and asynchronous patterns, which are critical for dealing with the unpredictable nature of browser APIs.

The Prompt:

Write a robust set of functions in a background service worker for advanced tab and window management. The goal is to build a session management feature.

The code must:
1.  **Query Tabs:** Create a function `getTabsByDomain(domain)` that returns a promise resolving to an array of tab objects matching the given domain.
2.  **Create Windows:** Create a function `createWorkspaceWindow(url)` that opens a new window with a specific URL and returns its window ID. It should handle errors like the user disabling pop-ups.
3.  **Group Tabs:** Create an async function `groupTabsByDomain()` that queries all open tabs, groups them by their domain (e.g., all github.com tabs in one group, all youtube.com in another), and uses `chrome.tabs.group` to visually group them. Include a check to avoid creating empty groups.
4.  **Event Handling:** Add a listener for `chrome.tabs.onCreated` that automatically adds any new tab to a specific group if its URL matches a predefined pattern.
5.  **Error Handling:** Wrap all `chrome` API calls in `try...catch` blocks and log meaningful errors to the console.

Please provide the full code for the background service worker, including all necessary listeners and helper functions.

Why this prompt is expert-level:

  • It demands asynchronous safety: By asking for promises and async/await, you’re instructing the AI to generate non-blocking code, which is essential for a responsive background script.
  • It enforces robustness: The requirement for try...catch blocks is a non-negotiable best practice. Browser APIs can fail for many reasons (permissions, user action), and this prompt ensures your extension won’t crash silently.
  • It combines multiple APIs: It forces the AI to reason about the interplay between tabs, windows, and tabs.group APIs, producing a cohesive solution rather than isolated snippets. A real-world “golden nugget” here is the onCreated listener, which demonstrates a proactive, event-driven architecture instead of a reactive one.

Prompt 11: Integrating with External APIs

Connecting to an external API is a common requirement, but it’s also a major security pitfall for Chrome extensions. Exposing API keys in your frontend code or content scripts is a critical vulnerability. The correct Manifest V3 pattern is to handle all network requests and authentication from the background service worker, using secure storage for credentials.

This prompt guides the AI to implement a secure, production-ready API integration layer, including the notoriously tricky OAuth 2.0 flow.

The Prompt:

Generate a secure background service worker module for handling API requests to a third-party service (e.g., "api.example.com"). The implementation must follow Manifest V3 security best practices.

Requirements:
1.  **Secure Storage:** Demonstrate how to securely store an API key or an OAuth refresh token using `chrome.storage.session`. Explain why this is safer than `localStorage` or hardcoding.
2.  **Fetch Wrapper:** Create an async function `callExternalAPI(endpoint, method, body)` that acts as a wrapper around the `fetch` API. It must:
    *   Retrieve the stored token from `chrome.storage.session`.
    *   Attach the token to the `Authorization` header (e.g., `Bearer <token>`).
    *   Include robust error handling for network failures and API-specific error codes (e.g., 401 Unauthorized).
3.  **OAuth 2.0 Flow:** Outline the logic for handling an OAuth 2.0 flow. This should involve:
    *   A function to generate the initial authorization URL.
    *   A listener for `chrome.identity.launchWebAuthFlow` to capture the redirect and extract the authorization code.
    *   A function to exchange the authorization code for an access token and refresh token via a `POST` request to the API's token endpoint.
    *   A function to securely store the received tokens.
4.  **Security Note:** Add a comment explaining why this entire process must happen in the background script and never in a content script or popup.

Provide the complete code for the background service worker module.

Why this prompt is expert-level:

  • It prioritizes security from the start: The prompt explicitly directs the AI to use chrome.storage.session and explains the “why,” building secure habits into the generated code. This is a crucial distinction from developers who might use local storage and expose tokens.
  • It covers the full OAuth lifecycle: It doesn’t just ask for a fetch request; it asks for the complete, multi-step OAuth dance. This is a complex flow that is difficult to implement correctly from scratch, and the prompt ensures all steps are covered.
  • It enforces architectural boundaries: The final security note is a “golden nugget” that reinforces the core security model of Chrome extensions. It teaches the developer why the architecture is designed this way, preventing them from making a common and dangerous mistake.

Prompt 12: Offscreen Document Creation for Heavy Lifting

Service workers in Manifest V3 are ephemeral—they can be terminated at any time to save resources. This makes them unsuitable for long-running tasks or tasks that require a DOM, like parsing HTML or processing audio. The Offscreen Documents API solves this by allowing you to create a hidden, invisible document that can perform these tasks without interrupting the user.

This prompt generates the code to set up and communicate with an offscreen document, a powerful pattern for advanced extensions.

The Prompt:

Write the complete code for a background service worker that uses the Offscreen Documents API to parse HTML from a fetched webpage.

The implementation must:
1.  **Setup:** Create a function `setupOffscreenDocument()` that checks if an offscreen document already exists. If not, it creates one using `chrome.offscreen.createDocument()`. It should specify the `reason` (e.g., "DOM_PARSER") and the `url` of a simple HTML file to load.
2.  **Message Passing:** Implement a message listener in the background script that waits for a request to parse HTML.
3.  **Offscreen Logic:** Provide the JavaScript code that would live inside the offscreen document. This script should:
    *   Listen for messages from the background script containing a raw HTML string.
    *   Use the DOM API (e.g., `DOMParser`) to parse the string.
    *   Extract specific data (e.g., all `<h2>` headings).
    *   Send the extracted data back to the background script using `chrome.runtime.sendMessage`.
4.  **Orchestration:** Show the background script function that initiates the entire flow: it calls `setupOffscreenDocument`, then sends the parsed HTML data to the offscreen document, and finally waits for the response with the extracted data.

Include all message passing logic and ensure the code is resilient to the offscreen document not being ready immediately.

Why this prompt is expert-level:

  • It solves a critical Manifest V3 limitation: The prompt directly addresses the “DOM access” problem in service workers, providing a modern, API-compliant solution.
  • It demonstrates a complete, asynchronous workflow: The prompt requires orchestration between the background script and the offscreen document. It forces the AI to generate code that handles the full request-response cycle across two different execution contexts, which is a complex pattern to get right.
  • It includes state management: The instruction to check if the offscreen document already exists before creating it is a vital performance optimization. This is a subtle but important detail that prevents errors and redundant creation, showcasing an understanding of the API’s lifecycle. This is the kind of “golden nugget” that separates a basic implementation from a professional one.

Section 5: Debugging, Testing, and Deployment

Even with the most meticulously planned architecture, the reality of development is that bugs are inevitable. The true test of a professional developer isn’t whether they write perfect code on the first try, but how efficiently they can debug, test, and prepare their work for production. In the Chrome extension ecosystem, this means mastering Chrome’s specific APIs, understanding how to simulate user environments, and navigating the Chrome Web Store’s submission process. A single unhandled chrome.runtime.lastError can crash your extension, while a missing privacy policy can trigger an instant rejection from the store. This is where your partnership with Claude Code shifts from architect to quality assurance engineer and launch manager.

Prompt 13: Generating a Bulletproof Test Suite with Jest

Testing Chrome extensions is notoriously difficult because your code runs in isolated contexts (popup, background, content script) and relies on browser APIs that don’t exist in a standard Node.js environment. A naive attempt to run jest will fail immediately because chrome is not defined. This prompt is engineered to overcome that specific hurdle by instructing the AI to build a sophisticated mocking layer from the ground up.

The Prompt:

Generate a comprehensive test suite for my Chrome extension using Jest and a modern testing library like @testing-library/react for the UI components.

**Extension Structure:**
- Background script: Manages state using `chrome.storage.local` and handles messages from the popup via `chrome.runtime.onMessage`.
- Popup: A React app that dispatches messages to the background script and updates its UI based on the response.
- Content Script: Injects a UI element into a webpage and listens for events.

**Test Requirements:**
1.  **Mock Chrome APIs:** Create a manual mock for `chrome` in a `__mocks__` directory. The mock must simulate:
    - `chrome.storage.local.get` and `chrome.storage.local.set` with a fake in-memory store.
    - `chrome.runtime.sendMessage` and `chrome.runtime.onMessage` to test the message passing flow between components.
    - `chrome.tabs.query` to mock active tab information.
2.  **Unit Tests for Background Logic:** Write tests for the background script's message listener. For example, a test should verify that when a "SAVE_DATA" message is received, `chrome.storage.local.set` is called with the correct payload.
3.  **Integration Tests for Popup:** Write tests that render the popup component. Simulate a user clicking a button that triggers `chrome.runtime.sendMessage`. Assert that the component's state updates correctly upon receiving a mocked response. Use `waitFor` to handle asynchronous state changes.
4.  **Content Script Interaction:** Write a test for the content script that verifies it injects the correct DOM element into a test fixture. Mock `chrome.runtime.onMessage` to simulate the background script sending a command to the content script (e.g., "HIGHLIGHT_ELEMENT") and assert the DOM is updated accordingly.

Please provide the full code for the mock files, the test files, and any necessary `jest.config.js` setup to make this work.

Why this prompt works:

  • It Solves the Core Problem First: The explicit instruction to create a manual mock for the chrome API is the most critical part. Without this, the entire test suite is impossible. This prompt forces the AI to build the necessary infrastructure, saving you hours of frustrating configuration.
  • It Mirrors Real-World Architecture: By testing the message passing flow, you’re validating the most common point of failure in extensions. A test that confirms sendMessage triggers the correct onMessage handler and updates the UI is worth ten tests of simple functions.
  • A Golden Nugget for MV3: The prompt’s focus on chrome.storage mocking is a subtle but crucial detail. In Manifest V3, the background script is a service worker, which is ephemeral. Your tests must prove that state is being persisted correctly, as this is the backbone of your extension’s functionality. This prompt builds that confidence directly into your workflow.

Prompt 14: The “Fix My Code” Debugging Prompt

When an extension fails, Chrome’s error console can be cryptic. The infamous Unchecked runtime.lastError message often appears without a clear stack trace, leaving you to guess whether the error is in the background script, the content script, or the message payload itself. A vague prompt like “fix this bug” will only lead to generic advice. This structured prompt acts as a diagnostic checklist, forcing you to provide the necessary context for a precise, actionable solution.

The Prompt:

Act as an expert Chrome extension debugger. I am encountering a runtime error and need a diagnosis and a refactored solution.

**The Error Log:**
[Paste the exact error message from the Chrome Developer Tools console here, including the stack trace if available]

**The Buggy Code:**
[Paste the specific function or file where you believe the error originates]

**Context & Environment:**
- **Extension Type:** Manifest V3
- **Involved Components:** (e.g., "Content script sends a message to the background script, which should update storage and send a response back.")
- **Trigger:** (e.g., "The error occurs when I click the extension's popup button.")
- **What I've Tried:** (e.g., "I added a `chrome.runtime.lastError` check in the `sendMessage` callback, but the error still persists.")

**Your Task:**
1.  **Diagnose the Root Cause:** Explain *why* this error is happening in the context of Chrome's asynchronous APIs and message passing security model. Identify the specific line of code that is failing.
2.  **Provide the Corrected Code:** Rewrite the provided code snippet to fix the bug. Ensure it includes proper error handling (e.g., `if (chrome.runtime.lastError)` checks for callbacks, `.catch()` for async/await).
3.  **Explain the Fix:** Briefly explain the changes you made and why they resolve the issue. For example, "The original code was missing a `return` statement after `chrome.tabs.query`, which caused the function to exit before sending a response."

Why this prompt works:

  • Forces Systematic Diagnosis: It transforms debugging from a guessing game into a structured process. By forcing you to define the environment, trigger, and what you’ve already tried, it eliminates ambiguity and prevents the AI from suggesting solutions you’ve already ruled out.
  • Targets Extension-Specific Pitfalls: The prompt explicitly asks for a diagnosis rooted in Chrome’s API model. This is key because most bugs in extensions are not JavaScript syntax errors; they are logic errors related to the asynchronous, event-driven nature of the browser environment (e.g., message ports closing unexpectedly, permissions issues).
  • Provides a Learning Opportunity: The request to “Explain the Fix” turns a simple bug fix into a teaching moment. It ensures you understand the why behind the solution, making you a better developer and helping you prevent similar bugs in the future. This is the difference between a temporary patch and permanent skill improvement.

Prompt 15: The Store-Ready Packaging Prompt

You’ve built it, you’ve tested it, and you’ve fixed the bugs. Now comes the final hurdle: convincing the Chrome Web Store reviewers that your extension is professional, secure, and valuable. This process is more than just zipping a folder; it’s about packaging, marketing, and legal compliance. A single missing screenshot or a vague description can delay your launch by days. This prompt streamlines the entire submission checklist into a single, powerful instruction.

The Prompt:

Prepare my Chrome extension for submission to the Chrome Web Store. I need a complete package and all required marketing and legal assets.

**Extension Details:**
- **Name:** [Your Extension Name]
- **One-line Description:** [A concise summary]
- **Detailed Description:** [A longer paragraph explaining features and benefits]
- **Key Features:** [A list of 3-5 bullet points]
- **Permissions Justification:** A list of all permissions requested in `manifest.json` (e.g., "storage", "activeTab", "scripting") and a one-sentence justification for each.

**Your Task:**
1.  **Generate the ZIP Package:** Provide a script or a list of commands to create a production-ready zip file of the `dist` or build directory, ensuring that no `node_modules`, `.env` files, or source maps are included.
2.  **Write the Store Description:** Synthesize the details above into a compelling, SEO-optimized store description. It should be formatted with Markdown for readability, include a clear call-to-action, and highlight the primary user benefit.
3.  **Create the Privacy Policy:** Generate a standard privacy policy text for a Chrome extension that explicitly states what data is collected (if any), how it's used, and that no data is shared with third parties. This must be compliant with Google's policies.
4.  **Promotional Assets Plan:** List the required promotional assets (icon, screenshots, promotional tile) with the correct dimensions and provide a brief creative brief for each. For example: "Screenshot 1 (1280x800): Show the extension's popup active on a popular website like Gmail, demonstrating its core feature."

Why this prompt works:

  • It’s a Complete Submission Checklist: This prompt doesn’t just do one thing; it orchestrates the entire launch process. It addresses the technical (zip script), the marketing (store description), the legal (privacy policy), and the visual (assets). This holistic approach prevents you from forgetting a critical step.
  • Builds a Defense Against Rejection: The “Permissions Justification” section is a pro-move. Chrome Web Store reviewers are increasingly strict about permission usage. By pre-writing clear, honest justifications, you are proactively answering the reviewer’s most important question, dramatically reducing the chance of a rejection for “insufficient justification.”
  • A Golden Nugget for Launch Success: The prompt’s request for a “creative brief” for the promotional assets is an expert-level touch. Most developers just upload random screenshots. By guiding you to create screenshots that demonstrate value on recognizable sites, the prompt helps you create marketing materials that convert browsers into users the moment they land on your store page.

Conclusion: Your AI-Powered Development Workflow

You’ve just witnessed how a strategic prompt library can compress weeks of development into hours. We’ve moved from abstract concepts to concrete, production-ready code—from defining the extension’s core architecture and secure message passing to crafting pixel-perfect UI components and implementing robust API integrations. This isn’t just about writing code faster; it’s about building with a higher degree of precision and foresight from the very beginning.

The landscape of software development is undergoing a fundamental shift. As we’ve seen, mastering prompt engineering is rapidly becoming as crucial a skill as writing the code itself. The prompts in this guide are more than just commands; they are blueprints for expertise. They allow a single developer to operate with the foresight and efficiency of a larger team, effectively acting as an architect, a senior engineer, and a QA tester all at once. This is the new competitive edge.

Your journey doesn’t end here. The real power comes from iteration and application.

Your next step is simple: Choose one prompt from this library—the one that solves your most immediate challenge. Copy it, run it, and then experiment. Tweak the parameters to fit your unique project. See how the AI adapts.

This is how you’ll build your intuition for what makes a great prompt. Start building the next generation of Chrome extensions with this AI-powered workflow and join the community of developers who are no longer just coding, but architecting the future of the web.

Critical Warning

The 'Prompt-First' Architecture

Never start with code; start with a blueprint. By prompting the AI to define the data flow and file structure first, you eliminate 90% of the architectural bugs that plague Chrome extensions. This 'Prompt-First' approach ensures your message passing is secure and scalable before you write a single line of logic.

Frequently Asked Questions

Q: Why do most Chrome extensions fail during development

Most extensions fail due to architectural issues, specifically insecure message passing between components and messy manifest.json files, rather than logic errors

Q: How does Claude Code improve Manifest V3 compliance

Claude Code acts as an expert partner that generates robust boilerplate and enforces security patterns, such as proper message passing and permission management, which are easy to miss manually

Q: What is the ‘Master Architect Blueprint’ prompt used for

This prompt forces the AI to generate a complete file structure, component roles, and data flow diagram before coding begins, preventing tight coupling and scalability issues

Stay ahead of the curve.

Join 150k+ engineers receiving weekly deep dives on AI workflows, tools, and prompt engineering.

AIUnpacker

AIUnpacker Editorial Team

Verified

Collective of engineers, researchers, and AI practitioners dedicated to providing unbiased, technically accurate analysis of the AI ecosystem.

Reading Best AI Prompts for Chrome Extension Development with Claude Code

250+ Job Search & Interview Prompts

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