DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Build a Text-to-Speech Chrome Extension

Why a Text‑to‑Speech Chrome Extension?

If you’ve ever wished you could listen to a web article while you’re commuting, or needed an accessibility boost for a web app you’re building, a Text‑to���Speech (TTS) Chrome extension is the perfect solution. With a few dozen lines of JavaScript you can turn any selected text into natural‑sounding speech, and thanks to modern voice AI services you can even clone your own voice.

In this post we’ll walk through a minimal, production‑ready extension that:

  1. Detects selected text on any page.
  2. Calls a TTS API (we’ll use ElevenLabs – a top‑tier voice synthesis platform).
  3. Plays the audio back to the user via the Chrome extension popup.

The result is a lightweight, privacy‑friendly tool you can ship to your users or keep for personal use.


Prerequisites

  • Node.js (for optional bundling, but not required).
  • A free ElevenLabs API key – sign up at the affiliate link below and grab your key from the dashboard.
  • Basic familiarity with Chrome extension development (manifest v3, service workers, etc.).

👉 Get started with ElevenLabs here: https://try.elevenlabs.io/kr07zfuqn1bp


Project Structure

tts-extension/
├─ manifest.json
├─ popup.html
├─ popup.js
├─ background.js
└─ icons/
   └─ icon-48.png
Enter fullscreen mode Exit fullscreen mode

We’ll keep everything in the same folder for simplicity.


1. Manifest – the Extension Blueprint

Create manifest.json and paste the following. This tells Chrome we’re using Manifest V3, defines a browser action (the popup), and grants the permissions we need.

{
  "manifest_version": 3,
  "name": "Quick TTS",
  "description": "Select text → click the icon → hear it spoken instantly.",
  "version": "1.0.0",
  "icons": {
    "48": "icons/icon-48.png"
  },
  "permissions": [
    "activeTab",
    "scripting",
    "storage"
  ],
  "action": {
    "default_popup": "popup.html",
    "default_icon": "icons/icon-48.png"
  },
  "background": {
    "service_worker": "background.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

Key points:

  • activeTab lets us inject a small content script to read the selection.
  • scripting is required for the new chrome.scripting.executeScript API in MV3.

2. Popup UI

popup.html is the tiny UI that appears when you click the extension icon.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Quick TTS</title>
  <style>
    body { font-family: Arial, sans-serif; width: 250px; padding: 10px; }
    button { width: 100%; padding: 8px; margin-top: 8px; }
    textarea { width: 100%; height: 80px; resize: none; }
  </style>
</head>
<body>
  <textarea id="selectedText" placeholder="Select text on the page…" readonly></textarea>
  <button id="speakBtn">🔊 Speak</button>

  <script src="popup.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

The textarea simply displays what the user has selected; the button triggers the synthesis.


3. Background Service Worker

background.js does two things: it fetches the selected text from the active tab, and it forwards the text to the ElevenLabs API when the popup asks for it.

// background.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.type === 'GET_SELECTION') {
    // Inject a one‑off script to read the selection
    chrome.scripting.executeScript(
      {
        target: { tabId: sender.tab.id },
        func: () => window.getSelection().toString(),
      },
      (injectionResults) => {
        const selected = injectionResults?.[0]?.result || '';
        sendResponse({ selected });
      }
    );
    // Must return true to use async sendResponse
    return true;
  }

  if (msg.type === 'SPEAK_TEXT') {
    const { text, voiceId, apiKey } = msg.payload;
    fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`, {
      method: 'POST',
      headers: {
        'xi-api-key': apiKey,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        text,
        model_id: 'eleven_monolingual_v1',
        voice_settings: { stability: 0.75, similarity_boost: 0.85 }
      })
    })
      .then(res => res.arrayBuffer())
      .then(buffer => {
        // Convert to a Blob URL and send back to the popup
        const blob = new Blob([buffer], { type: 'audio/mpeg' });
        const url = URL.createObjectURL(blob);
        sendResponse({ audioUrl: url });
      })
      .catch(err => {
        console.error('ElevenLabs error', err);
        sendResponse({ error: err.message });
      });

    return true; // async response
  }
});
Enter fullscreen mode Exit fullscreen mode

Note: The endpoint /v1/text-to-speech/{voice_id} is the core ElevenLabs API. Replace voiceId with any of the default voices or a voice you’ve cloned in your ElevenLabs dashboard.


4. Popup Logic

popup.js wires everything together: it pulls the selection, displays it, and plays back the generated audio.

// popup.js
const textarea = document.getElementById('selectedText');
const speakBtn = document.getElementById('speakBtn');

// Replace with your own ElevenLabs API key (store securely!)
const ELEVEN_API_KEY = ''; // ← paste your key here
const DEFAULT_VOICE = 'EXAVITQu4vr4xnSDxMaL'; // example voice ID

// 1️⃣ Get selected text from the active tab
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
  const tab = tabs[0];
  chrome.runtime.sendMessage(
    { type: 'GET_SELECTION' },
    (response) => {
      textarea.value = response.selected || 'No text selected.';
    }
  );
});

// 2️⃣ When the user clicks "Speak"
speakBtn.addEventListener('click', () => {
  const text = textarea.value.trim();
  if (!text) return alert('Select some text first!');

  speakBtn.disabled = true;
  speakBtn.textContent = '🔄 Generating…';

  chrome.runtime.sendMessage(
    {
      type: 'SPEAK_TEXT',
      payload: {
        text,
        voiceId: DEFAULT_VOICE,
        apiKey: ELEVEN_API_KEY,
      },
    },
    (resp) => {
      speakBtn.disabled = false;
      speakBtn.textContent = '🔊 Speak';

      if (resp.error) {
        return alert('Error: ' + resp.error);
      }

      const audio = new Audio(resp.audioUrl);
      audio.play();
    }
  );
});
Enter fullscreen mode Exit fullscreen mode

Storing the API Key Securely

For a production extension you’d want to avoid hard‑coding the key. The simplest approach is to use Chrome’s storage.sync API and a small options page where the user can paste their ElevenLabs key. The code above keeps things short for the tutorial, but the concept is the same.


5. Voice Cloning – Make It Personal

ElevenLabs shines when you upload a few minutes of your own voice and get a cloned voice model. The workflow is:

  1. Record a short (30‑60 s) voice sample.
  2. Upload it to the ElevenLabs dashboard (the affiliate link below takes you straight there).
  3. Once the model is ready, copy its voice_id and replace DEFAULT_VOICE in popup.js.

Your extension will now read text in your voice – perfect for podcasts, audiobooks, or just a fun personal touch.

👉 Try cloning your voice with ElevenLabs: https://try.elevenlabs.io/kr07zfuqn1bp


6. Testing the Extension

  1. Open Chrome → chrome://extensions/.
  2. Enable Developer mode (top‑right toggle).
  3. Click Load unpacked and select the tts-extension folder.
  4. Pin the extension icon, go to any webpage, select a paragraph, and click the icon → Speak.

If everything is wired correctly you’ll hear the synthesized audio playing through your speakers. Open the console (Ctrl + Shift + J) if you run into errors – the most common issue is a missing or invalid ElevenLabs API key.


7. Going Further

  • Multiple voices – expose a dropdown in the popup that lists the voices you own in ElevenLabs.
  • Cache audio – store generated URLs in chrome.storage.local to avoid re‑synthesizing the same sentence.
  • Background playback – let the user keep listening while they navigate to other tabs (use the chrome.audio API or a hidden audio element in the background service worker).
  • Rate‑limit handling – ElevenLabs allows a generous number of requests per month, but you might want to throttle calls for a public extension.

Wrap‑up

Building a Text‑to‑Speech Chrome extension is a great way to dip your toes into voice AI, and with ElevenLabs you get access to some of the most natural‑sounding voices on the market – even your own. The code above is deliberately minimal so you can adapt it to your own product, add UI polish, or integrate it into a larger web app.

Ready to give your users (or yourself) a voice? Grab an ElevenLabs API key, clone a voice if you like, and fire up the extension. Happy coding, and may your apps always speak clearly!

Try ElevenLabs today and bring high‑quality TTS to your projects: https://try.elevenlabs.io/kr07zfuqn1bp

Top comments (0)