AiCredits
Dev Guide

Browser Extensions Powered by LLMs: Manifest V3 Architecture

Build browser extensions powered by LLMs on Manifest V3: service-worker streaming, safe API key storage, and real working code with deepseek-v4-flash.

Published 2026-12-03 Updated 2026-12-03 9 min

Why Manifest V3 Breaks the Obvious LLM Extension Design

Manifest V3 replaced the persistent background page with a service worker that Chrome is free to stop whenever it goes idle. That single change invalidates most LLM extension tutorials, which quietly assume a long-lived process holding an API client instance, an in-memory conversation array, and an open connection to the model.

The correct fix is architectural rather than a hack around the lifecycle. Put every model call in the service worker, stream deltas to a UI surface over a Port, persist anything you would have kept in a variable, and make the UI able to re-attach to a request that is still in flight. The skeleton below is the one to copy.

The Four Contexts and What Each Can Actually Do

ContextDOM accessCan call the APIWhere the key lives
Service workerNoYes — host_permissions bypasses CORSRead from chrome.storage.local per request
Side panel / popupYesYes, but keep network work in the workerNever — ask the worker
Content scriptYes, the page's DOMUsually blocked: it inherits the page origin and hits CORSNever, under any circumstances
Offscreen documentYesYesNo

A Minimal Manifest

{
  "manifest_version": 3,
  "name": "Page Explainer",
  "version": "1.0.0",
  "description": "Summarise any page in a streaming side panel.",
  "permissions": ["storage", "activeTab", "scripting", "sidePanel"],
  "host_permissions": ["https://api.aicreditsapi.com/*"],
  "background": { "service_worker": "background.js", "type": "module" },
  "action": { "default_title": "Open Page Explainer" },
  "side_panel": { "default_path": "sidepanel.html" },
  "options_page": "options.html"
}

Two things this manifest does not do by itself. First, clicking the toolbar icon only opens the side panel if the worker registers the behaviour: call chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }) once at the top level of background.js. Second, activeTab is granted by that icon click — if a user opens the panel and then switches tabs, injecting into the new tab will fail until you declare a narrower host permission for the sites you care about.

Rule One: the API Key Never Ships in the Bundle

Anyone can unzip a published extension and read every file in it. An API key inlined into the bundle is a key you have donated to the internet. Ship an options page that writes a user-supplied key into chrome.storage.local (not sync — it crosses devices and has tight quotas), and have the service worker read it fresh for each request.

Be honest about what storage gives you: chrome.storage.local is not encrypted, and anything running inside your extension can read it. That is acceptable for a developer tool where the user pastes their own credential. If the key is yours — a commercial product with a shared account — do not store it on the client at all. Put a small proxy in front and let the extension talk to that.

Background Worker: Streaming with deepseek-v4-flash

Use raw fetch here rather than a bundled SDK. Service workers have no XMLHttpRequest, and the model API is a plain JSON POST with server-sent events coming back, so the SDK mainly adds bundle weight and a browser-safety flag. The stream parser below handles the awkward part: SSE events arriving split across network chunks.

// background.js — MV3 service worker (type: module)
const API_URL = "https://api.aicreditsapi.com/v1/chat/completions";

chrome.runtime.onConnect.addListener((port) => {
  if (port.name !== "llm") return;

  const controller = new AbortController();
  let alive = true;
  const send = (msg) => { if (alive) port.postMessage(msg); };

  port.onDisconnect.addListener(() => {
    alive = false;
    controller.abort(); // stop paying for tokens nobody will read
  });

  port.onMessage.addListener(async (msg) => {
    if (msg.type !== "ask") return;

    const { apiKey } = await chrome.storage.local.get("apiKey");
    if (!apiKey) {
      send({ type: "error", message: "Add your API key on the options page." });
      return;
    }

    try {
      const res = await fetch(API_URL, {
        method: "POST",
        signal: controller.signal,
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${apiKey}`,
        },
        body: JSON.stringify({
          model: "deepseek-v4-flash",
          stream: true,
          messages: [
            { role: "system", content: "You summarise web pages in tight bullets." },
            { role: "user", content: msg.prompt },
          ],
        }),
      });

      if (!res.ok || !res.body) {
        send({ type: "error", message: `HTTP ${res.status}: ${await res.text()}` });
        return;
      }

      const reader = res.body.getReader();
      const decoder = new TextDecoder();
      let buffer = "";

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });

        const lines = buffer.split("\n");
        buffer = lines.pop() ?? ""; // keep the partial line for the next chunk

        for (const line of lines) {
          const trimmed = line.trim();
          if (!trimmed.startsWith("data:")) continue;
          const payload = trimmed.slice(5).trim();
          if (payload === "[DONE]") { send({ type: "done" }); return; }
          const delta = JSON.parse(payload).choices?.[0]?.delta?.content;
          if (delta) send({ type: "delta", text: delta });
        }
      }
      send({ type: "done" });
    } catch (err) {
      if (err.name !== "AbortError") send({ type: "error", message: String(err) });
    }
  });
});

Consuming the Stream in the Side Panel

The panel never touches the key or the network. It opens a Port, writes the deltas into a textContent node, and disables its button while a request is running. innerHTML here would be a cross-site scripting bug with a model as the attacker.

// sidepanel.js — a normal extension page, no inline <script> allowed
const log = document.getElementById("log");
const button = document.getElementById("ask");
let port = null;
let text = "";

function connect() {
  port = chrome.runtime.connect({ name: "llm" });

  port.onMessage.addListener((msg) => {
    if (msg.type === "delta") {
      text += msg.text;
      log.textContent = text;
    } else if (msg.type === "done") {
      button.disabled = false;
    } else if (msg.type === "error") {
      log.textContent = `Error: ${msg.message}`;
      button.disabled = false;
    }
  });

  port.onDisconnect.addListener(() => {
    port = null;
    button.disabled = false;
  });
}

button.addEventListener("click", async () => {
  button.disabled = true;
  text = "";
  log.textContent = "";
  if (!port) connect();

  try {
    const page = await pageText();
    port.postMessage({ type: "ask", prompt: `Summarise this page:\n\n${page}` });
  } catch (err) {
    log.textContent = `Could not read this page: ${err.message}`;
    button.disabled = false;
  }
});

connect();

Pulling Page Text Without Breaking the Page

Do not run a content script on <all_urls> that scrapes the DOM on every page load. That is a slow, privacy-hostile default and it scares users at install time. Inject on demand instead, using activeTab plus scripting.executeScript. The injected function is serialised into the page, so it cannot close over your variables — return plain data and nothing else.

// part of sidepanel.js
async function pageText() {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (!tab?.id) throw new Error("no active tab");

  const [injection] = await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    func: () => {
      const clone = document.body.cloneNode(true);
      clone.querySelectorAll("script, style, noscript, svg").forEach((n) => n.remove());
      return clone.innerText.replace(/\s+/g, " ").trim().slice(0, 8000);
    },
  });

  return injection.result ?? "";
}

Surviving Service Worker Restarts

  • Chrome shuts down an idle worker after roughly thirty seconds, and an open Port no longer guarantees immortality. Assume the worker dies between any two user actions.

  • Persist partial output to chrome.storage.session as it streams so a restarted worker can rehydrate the panel instead of showing an empty box.

  • An in-flight fetch is the one thing that reliably holds the worker open. Never await a long setTimeout as a keep-alive trick — that behaviour is explicitly not supported.

  • Abort on disconnect. Every Port you open should carry an AbortController, or a closed panel keeps a stream running and billing.

  • Keep exactly one Port per panel instance and never cache it in module scope across a reload of the panel page.

CSP: Bundle Everything, Load Nothing Remotely

MV3 extension pages cannot load remote code and cannot use eval. No CDN <script src>, no inline handlers, no new Function. Bundle your dependencies locally with esbuild and reference them as files. If you want to render markdown, bundle a parser plus a sanitiser such as DOMPurify and run it in the panel or in an offscreen document — never in the service worker, which has no DOM to sanitise with.

When the Key Is Yours, Add a Proxy

For a distributed product, the extension should call your own endpoint. The proxy holds the credential, enforces per-user rate limits, and lets you swap models without shipping a new extension build. Here is the whole thing for the AiCredits API, using the OpenAI SDK server-side where it belongs.

# proxy.py — pip install fastapi uvicorn openai
# run: uvicorn proxy:app --port 8787
import os
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

app = FastAPI()


@app.post("/explain")
def explain(payload: dict):
    def tokens():
        stream = client.chat.completions.create(
            model="deepseek-v4-flash",
            stream=True,
            messages=[
                {"role": "system", "content": "Explain the page in five bullets."},
                {"role": "user", "content": payload["text"][:8000]},
            ],
        )
        for chunk in stream:
            delta = chunk.choices[0].delta.content
            if delta:
                yield delta

    return StreamingResponse(tokens(), media_type="text/plain")

The extension side barely changes: point host_permissions at your proxy origin, drop the Authorization header, and POST {"text": ...} instead of the chat payload. AiCredits is worth a look for this because it is payable by card or PayPal without a Chinese phone number or bank account, so a solo developer outside mainland China can actually provision an account. Current rates live at aicreditsapi.com/deepseek-prices.

Choosing flash or pro Inside an Extension

  • Default everything to deepseek-v4-flash. Toolbar actions, hover explanations, rewrite-suggestion chips and per-paragraph summaries are latency-sensitive and short-context — flash is the right trade.

  • Escalate to deepseek-v4-pro only when one request has to reason across a whole document, reconcile several tabs, or produce a plan rather than a summary. Pro costs more per token, so gate it behind an explicit user action, not a background trigger.

  • Route by intent, not by page. A single summarise button and a single analyse deeply button is a clearer contract than a model picker in a popup.

  • Cache aggressively. Hash the extracted text and keep the result in chrome.storage.local. Identical prompt prefixes hit the provider's context cache and cost less, and a cache hit costs nothing at all.

  • Off-peak requests cost less than peak ones, which matters for anything you run on a schedule — batch overnight re-indexing rather than firing on every page load.

FAQ

Can a content script call the LLM API directly?

It can try, but the request is issued against the host page's origin, so it is subject to that page's CORS policy and will usually be blocked. Do the fetch in the service worker, where declared host_permissions lift CORS, and stream results back over a Port.

Does Manifest V3 break streaming responses?

No. fetch with a ReadableStream body works inside the service worker. You simply have to parse the SSE frames yourself and forward each delta with port.postMessage, which is what the parser above does.

Is chrome.storage.local safe for an API key?

It is readable by anyone with access to the browser profile and by any code in your extension, and it is not encrypted. Fine when the user supplies their own key. For a commercial product, proxy through your own server so the credential never reaches the client.

Should the extension use the OpenAI SDK or raw fetch?

In the worker, raw fetch is leaner and gives you direct access to the stream. On the server, the SDK is the better choice — the proxy example above uses it with base_url set to the AiCredits endpoint and model set to deepseek-v4-flash.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

Was this article helpful?

| Share on X Reddit Copy link
💬
反馈意见 / Feedback ×