How to Use Transformers.js in a Chrome Extension

Hugging Face Blog Tools

Summary

This article provides a technical guide on integrating Transformers.js into a Chrome extension using Manifest V3, detailing architecture for background service workers, model caching, and agent loops.

No content available
Original Article
View Cached Full Text

Cached at: 05/08/26, 09:02 AM

How to Use Transformers.js in a Chrome Extension

Source: https://huggingface.co/blog/transformersjs-chrome-extension Back to Articles

Nico Martin’s avatar

We recently released a Transformers.js demo browser extension powered byGemma 4 E2Bto help users navigate the web.

While building it, we ran into several practical observations about Manifest V3 runtimes, model loading, and messaging that are worth sharing.

https://huggingface.co/blog/transformersjs-chrome-extension#who-this-is-forWho this is for

This guide is for developers who want to run local AI features in a Chrome extension with Transformers.js under Manifest V3 constraints.

By the end, you will have the same architecture used in this project: a background service worker that hosts models, a side panel chat UI, and a content script for page-level actions.

https://huggingface.co/blog/transformersjs-chrome-extension#what-we-will-buildWhat we will build

In this guide, we will recreate the core architecture ofTransformers.js Gemma 4 Browser Assistant, using the published extension as a reference and the open-source codebase as the implementation map.

https://huggingface.co/blog/transformersjs-chrome-extension#1-chrome-extension-architecture-mv31) Chrome extension architecture (MV3)

Before diving in, a quick scope note: I will not go deep on the React UI layer or Vite build configuration. The focus here is the high-level architecture decisions: what runs in each Chrome runtime and how those pieces are orchestrated.

If Manifest V3 is new to you, read this short overview first:What is Manifest V3?.

https://huggingface.co/blog/transformersjs-chrome-extension#11-runtime-contexts-and-entry-points1.1 Runtime contexts and entry points

In MV3, your architecture starts inpublic/manifest\.json. This project defines three entry points:

The background service worker also handleschrome\.action\.onClickedto open the side panel for the active tab. Related entry point to know: a popup can be defined withaction\.default\_popupand works well for quick actions. This project uses a side panel for persistent chat, but the orchestration pattern is the same.

https://huggingface.co/blog/transformersjs-chrome-extension#12-what-runs-where1.2 What runs where

The key design decision is to keep heavy orchestration in the background and keep UI/page logic thin.

  • Background (src/background/background\.ts) is the control plane: agent lifecycle, model initialization, tool execution, and shared services like feature extraction.
  • Side panel (src/sidebar/\*) is the interaction layer: chat input/output, streaming updates, and setup controls.
  • Content script (src/content/content\.ts) is the page bridge: DOM extraction and highlight actions.

One practical consequence of this division is that the conversation history also lives in background (Agent\.chatMessages): the UI sends events likeAGENT\_GENERATE\_TEXT, background appends the message, runs inference, then emitsMESSAGES\_UPDATEback to the side panel.

This split avoids duplicate model loads, keeps the UI responsive, and respects Chrome’s security boundaries around DOM access.

https://huggingface.co/blog/transformersjs-chrome-extension#13-messaging-contract1.3 Messaging contract

Once runtimes are separated, messaging becomes the backbone. In this project, all messages are typed through enums insrc/shared/types\.ts.

  • Side panel -> background (BackgroundTasks):- CHECK\_MODELS,INITIALIZE\_MODELS - AGENT\_INITIALIZE,AGENT\_GENERATE\_TEXT,AGENT\_GET\_MESSAGES,AGENT\_CLEAR - EXTRACT\_FEATURES
  • Background -> side panel (BackgroundMessages):- DOWNLOAD\_PROGRESS,MESSAGES\_UPDATE
  • Background -> content (ContentTasks):- EXTRACT\_PAGE\_DATA,HIGHLIGHT\_ELEMENTS,CLEAR\_HIGHLIGHTS

The orchestration rule is simple: the background is the single coordinator; side panel and content script are specialized workers that request actions and render results.

Typical request flow:

  1. Side panel sendsAGENT\_GENERATE\_TEXT.
  2. Background appends toAgent\.chatMessagesand runs model/tool steps.
  3. Background emitsMESSAGES\_UPDATE.
  4. Side panel re-renders from the updated message list.

https://huggingface.co/blog/transformersjs-chrome-extension#2-transformersjs-integration-details2) Transformers.js integration details

https://huggingface.co/blog/transformersjs-chrome-extension#21-models-and-responsibilities2.1 Models and responsibilities

Insrc/shared/constants\.ts, this extension uses two model roles:

The split is intentional: Gemma 4 handles reasoning/tool decisions, while MiniLM generates vector embeddings for the semantic similarity search inask\_websiteandfind\_history.

https://huggingface.co/blog/transformersjs-chrome-extension#22-where-inference-runs2.2 Where inference runs

All inference runs in background (src/background/background\.ts):

  • text generation viapipeline\("text\-generation", \.\.\.\)with consistent KV Caching enabled by our newDynamicCacheclass
  • embeddings viapipeline\("feature\-extraction", \.\.\.\)plus vector normalization

This gives a single model host for all tabs/sessions, avoids duplicate memory usage, and keeps the side panel UI responsive. Because models are loaded from the background service worker, artifacts are cached under the extension origin (chrome\-extension://<extension\-id\>) rather than per-website origins, which gives one shared cache for the whole extension install.

MV3 lifecycle note: service workers can be suspended and restarted, so model runtime state should be treated as recoverable and re-initialized when needed.

https://huggingface.co/blog/transformersjs-chrome-extension#23-download-and-cache-lifecycle2.3 Download and cache lifecycle

The model lifecycle is explicit:

Permissions and privacy are part of the architecture, not a checkbox at the end. In this project,public/manifest\.jsonasks forsidePanel,storage,scripting, andtabs, plushost\_permissionsforhttp\(s\)://\*/\*:

  • sidePanel: required to open and control the side panel UX.
  • storage: required to persist tool/settings state across sessions.
  • tabs+scripting: required for tab-aware tools and page-level actions.
  • host\_permissionsonhttp\(s\)://\*/\*: required because content extraction/highlighting is designed to work on arbitrary websites.

Why keep this narrow: permissions define user trust and Chrome Web Store review risk. Request only what your features actually need, and state clearly that inference runs locally in the extension runtime so users understand where their data is processed.

https://huggingface.co/blog/transformersjs-chrome-extension#3-agent-and-tool-execution-loop3) Agent and tool execution loop

https://huggingface.co/blog/transformersjs-chrome-extension#31-tool-calling-basics-why-this-layer-exists3.1 Tool-calling basics (why this layer exists)

Before the execution loop, it helps to understand how model tool calling works (the basis for any agentic workflow). You pass messages plus a tool schema (name,description, andparameters), and Transformers.js formats the actual prompt from those inputs using the model’s chat template. Because chat templates are model-specific, the exact tool-call format depends on the model you use. With Gemma-4-style templates, the model emits a special tool-call token block when it decides to call one.

import { pipeline } from "@huggingface/transformers";

const generator = await pipeline(
  "text-generation",
  "onnx-community/gemma-4-E2B-it-ONNX",
  {
    dtype: "q4f16",
    device: "webgpu",
  },
);

const messages = [{ role: "user", content: "What's the weather in Bern?" }];

const output = await generator(messages, {
  max_new_tokens: 128,
  do_sample: false,
  tools: [
    {
      type: "function",
      function: {
        name: "getWeather",
        description: "Get the weather in a location",
        parameters: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "The location to get the weather for",
            },
          },
          required: ["location"],
        },
      },
    },
  ],
});

At generation time, the model can emit output like:

<|tool_call>call:getWeather{location:<|"|>Bern<|"|>}<tool_call|>

That is exactly why this project has a normalization layer (webMcp) and a parser (extractToolCalls): model output must be converted into deterministic tool executions.

https://huggingface.co/blog/transformersjs-chrome-extension#32-tool-interface-in-this-project3.2 Tool interface in this project

src/background/agent/webMcp\.tsxnormalizes extension tools into a model-friendly shape:

  • name,description,inputSchema,execute

Example tools includeget\_open\_tabs,go\_to\_tab,open\_url,close\_tab,find\_history,ask\_website, andhighlight\_website\_element.

https://huggingface.co/blog/transformersjs-chrome-extension#33-loop-design-agentrunagent3.3 Loop design (Agent\.runAgent)

The core design choice here is to separate internal model messages from UI-facing chat messages:

  • Internal model transcript (messages): system/user/tool/assistant turns used for messages ingenerator\(\.\.\.\).
  • UI transcript (chatMessages): what the user sees, including streamed assistant text plus tool execution metadata (tools) and performance metrics.

Execution flow:

  1. Add user input tochatMessages, create a placeholder assistant message, and stream tokens.
  2. Parse streamed/final model output withextractToolCalls\.tsinto\{ message, toolCalls \}.
  3. Keep the user-visible assistant message as plain text, while tool calls execute in background.
  4. Append tool results to the assistant tool metadata and feed results back as the next prompt turn.
  5. Repeat until no tool calls remain, then finalize assistant content + metrics.

This keeps user communication clean while preserving a deterministic tool loop in the background.

https://huggingface.co/blog/transformersjs-chrome-extension#4-data-boundaries-and-persistence4) Data boundaries and persistence

State placement is another architectural decision that matters a lot in MV3. In this implementation, state is split by lifecycle and access pattern:

  • Conversation state: background memory (Agent\.chatMessages) for fast turn-by-turn orchestration.
  • Tool preferences:chrome\.storage\.localso settings persist across sessions.
  • Semantic history vectors: IndexedDB (VectorHistoryDB) for larger local retrieval data.
  • Extracted page content: background cache (WebsiteContentManager) keyed by active URL.

As described in section 1.2, keeping conversation history in background gives one canonical state across UI updates. This keeps short-lived state in memory, durable settings in extension storage, and heavy retrieval data in a local database.

https://huggingface.co/blog/transformersjs-chrome-extension#5-build-and-packaging-notes5) Build and packaging notes

You do not need a complex build setup, but MV3 does require predictable outputs for each runtime.

The goal is simple: one artifact per Chrome entry point, in the exact placepublic/manifest\.jsonexpects.

https://huggingface.co/blog/transformersjs-chrome-extension#final-takeawayFinal takeaway

The architecture choice that unlocks this whole project is clear separation of concerns: background owns orchestration and model execution, UI surfaces stay thin, and content scripts handle page access.

This project uses a side panel, but the same approach works for other setups:

  • Popup-first assistant: useaction\.default\_popupfor quick interactions, with background owning conversation state and model execution.
  • Side-panel copilot: keep long-running conversations in a persistent panel while background handles tool loops and caching.
  • Per-tab agents: keep one agent state pertabIdin background when each tab should have its own context.
  • Hybrid UI (popup + side panel + options page): all UI entry points talk to the same background coordinator and reuse the same message contracts.

The practical rule is simple: decide where state lives (global,tabId, or site-scoped), keep that state and the model inference in background (basically as background services), and let UI/content runtimes act as focused clients.

Similar Articles

Building a UMatrix Replacement

Hacker News Top

This article explores options for replacing the deprecated uMatrix browser extension under Chrome's Manifest V3, proposing a solution using declarativeNetRequest and Content Security Policy to control site permissions and subresource requests.