DailyGlimpse

Build a Chrome Extension with Transformers.js: A Step-by-Step Guide

AI
April 26, 2026 · 3:59 PM
Build a Chrome Extension with Transformers.js: A Step-by-Step Guide

Transformers.js brings state-of-the-art machine learning models directly to the browser. This guide shows how to integrate it into a Chrome extension for on-device AI tasks like text classification, sentiment analysis, or image processing.

Why Transformers.js for Chrome Extensions?

Running models in the browser eliminates server costs and latency. Users get instant results without sending data to external APIs – ideal for privacy-conscious tools.

Prerequisites

  • Basic knowledge of JavaScript and Chrome extension development.
  • Node.js and npm installed.
  • A Chrome browser for testing.

Step 1: Initialize the Extension

Create a new directory and a manifest.json:

{
  "manifest_version": 3,
  "name": "AI Assistant",
  "version": "1.0",
  "permissions": ["activeTab"],
  "action": {
    "default_popup": "popup.html"
  }
}

Step 2: Install Transformers.js

In your extension root, run:

npm install @xenova/transformers

Use a bundler like Webpack or Vite to compile the code into a single file that Chrome can load.

Step 3: Create the Popup

popup.html with a button and output area.

<!DOCTYPE html>
<html>
<body>
  <h1>AI Assistant</h1>
  <button id="classify">Analyze Text</button>
  <p id="result"></p>
  <script src="popup.js"></script>
</body>
</html>

Step 4: Implement the AI Logic

In popup.js, load the pipeline and run inference:

import { pipeline } from '@xenova/transformers';

let classifier;
document.getElementById('classify').addEventListener('click', async () => {
  if (!classifier) {
    classifier = await pipeline('sentiment-analysis');
  }
  const result = await classifier('I love Transformers.js!');
  document.getElementById('result').innerText = result[0].label;
});

Step 5: Bundle and Load

  1. Build your project with your bundler (e.g., npm run build).
  2. Go to chrome://extensions and enable Developer mode.
  3. Click 'Load unpacked' and select your dist folder.
  4. Test the extension by clicking its icon and the 'Analyze Text' button.

Tips for Optimization

  • Use Quantized models to reduce size and speed up loading.
  • Cache the pipeline after first load to avoid re-downloading.
  • Limit initial model downloads by using smaller variants like distilbert-base-uncased-finetuned-sst-2-english.

Conclusion

Transformers.js opens a world of possibilities for Chrome extensions. You can now run AI models locally, providing fast and private experiences. Experiment with other pipelines like translation, question answering, or image classification to build powerful browser tools.