DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Build a Text-to-Speech Chrome Extension

Overview

Want to give your Chrome browsing experience a voice?

Building a Text‑to‑Speech (TTS) Chrome extension lets you read any page, highlight text, or even clone your own voice.

Below you’ll find a step‑by‑step guide that covers everything from the manifest to the API call, all while leveraging the powerful ElevenLabs TTS engine.


1. Why ElevenLabs?

ElevenLabs offers state‑of‑the‑art neural voices and easy‑to‑use APIs for voice cloning.

Their voice models sound natural, and the API is simple to integrate with a single HTTP request.

If you’re looking for high‑quality TTS that can even mimic your own voice, ElevenLabs is the tool of choice.

You can start for free at https://try.elevenlabs.io/kr07zfuqn1bp.


2. Project Structure

tts-extension/
├─ manifest.json
├─ background.js
├─ content.js
├─ popup.html
├─ popup.js
├─ options.html
├─ options.js
└─ icons/
   └─ icon.png
Enter fullscreen mode Exit fullscreen mode
  • manifest.json – declares the extension’s capabilities.
  • background.js – handles API calls and audio playback.
  • content.js – captures user selections and sends messages to the background.
  • popup.html / popup.js – quick UI for manual input.
  • options.html / options.js – store API key, voice preferences, etc.

3. Manifest (manifest.json)

{
  "manifest_version": 3,
  "name": "Text‑to‑Speech Reader",
  "description": "Read any page aloud using ElevenLabs TTS.",
  "version": "1.0",
  "icons": { "128": "icons/icon.png" },
  "permissions": ["storage", "activeTab", "scripting"],
  "background": { "service_worker": "background.js" },
  "action": {
    "default_popup": "popup.html",
    "default_icon": "icons/icon.png"
  },
  "options_page": "options.html",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Tip: Use Manifest V3 for better performance and security.


4. Options Page (options.html / options.js)

Create a simple form where users can paste their ElevenLabs API key and choose a default voice.

<!-- options.html -->
<!DOCTYPE html>
<html>
<head>
  <title>Extension Settings</title>
  <style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    label { display: block; margin-top: 10px; }
  </style>
</head>
<body>
  <h1>Settings</h1>
  <label>ElevenLabs API Key
    <input id="apiKey" type="text" placeholder="sk-..." />
  </label>
  <label>Default Voice ID
    <input id="voiceId" type="text" placeholder="voice_id" />
  </label>
  <button id="save">Save</button>
  <script src="options.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
// options.js
document.getElementById('save').onclick = async () => {
  const apiKey = document.getElementById('apiKey').value.trim();
  const voiceId = document.getElementById('voiceId').value.trim();
  await chrome.storage.sync.set({ apiKey, voiceId });
  alert('Saved!');
};
Enter fullscreen mode Exit fullscreen mode

5. Content Script (content.js)

The content script listens for a user’s text selection and sends it to the background script.

// content.js
document.addEventListener('mouseup', () => {
  const selection = window.getSelection().toString().trim();
  if (selection.length) {
    chrome.runtime.sendMessage({ type: 'speak', text: selection });
  }
});
Enter fullscreen mode Exit fullscreen mode

6. Background Script (background.js)

This is where the heavy lifting happens: fetch the API key, call ElevenLabs, and play the audio.

// background.js
const ELEVENLABS_URL = 'https://api.elevenlabs.io/v1/text-to-speech';

chrome.runtime.onMessage.addListener(async (msg, sender, sendResponse) => {
  if (msg.type !== 'speak') return;

  const { apiKey, voiceId } = await chrome.storage.sync.get(['apiKey', 'voiceId']);
  if (!apiKey) {
    console.warn('ElevenLabs API key missing');
    return;
  }

  const payload = {
    text: msg.text,
    voice_settings: { stability: 0.75, similarity_boost: 0.75 }
  };

  try {
    const res = await fetch(`${ELEVENLABS_URL}/${voiceId || 'alloy'}`, {
      method: 'POST',
      headers: {
        'xi-api-key': apiKey,
        'Content-Type': 'application/json',
        'Accept': 'audio/mpeg'
      },
      body: JSON.stringify(payload)
    });

    if (!res.ok) throw new Error(`API error: ${res.statusText}`);
    const blob = await res.blob();
    const url = URL.createObjectURL(blob);
    const audio = new Audio(url);
    audio.play();
  } catch (e) {
    console.error(e);
    // fallback to Web Speech API
    const synth = window.speechSynthesis;
    const utter = new SpeechSynthesisUtterance(msg.text);
    synth.speak(utter);
  }
});
Enter fullscreen mode Exit fullscreen mode

Why the fallback?

If the ElevenLabs call fails (e.g., no key or quota exceeded), the extension still reads text using the built‑in Web Speech API.


7. Popup UI (popup.html / popup.js)

A quick way to type text and hear it immediately.

<!-- popup.html -->
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: Arial, sans-serif; padding: 10px; }
    textarea { width: 100%; height: 80px; }
    button { margin-top: 10px; width: 100%; }
  </style>
</head>
<body>
  <textarea id="inputText" placeholder="Type text here..."></textarea>
  <button id="speakBtn">Speak</button>
  <script src="popup.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
// popup.js
document.getElementById('speakBtn').onclick = () => {
  const text = document.getElementById('inputText').value.trim();
  if (text) chrome.runtime.sendMessage({ type: 'speak', text });
};
Enter fullscreen mode Exit fullscreen mode

8. Voice Cloning (Optional)

ElevenLabs allows you to clone a voice by uploading a few samples.

Below is a minimal curl example; you can adapt it into JavaScript if you want to add a “Clone Voice” button.

curl -X POST "https://api.elevenlabs.io/v1/voice-cloning" \
  -H "xi-api-key: YOUR_API_KEY" \
  -H "Content-Type: multipart/form-data" \
  -F "audio_file=@sample1.wav" \
  -F "audio_file=@sample2.wav" \
  -F "voice_name=My Clone"
Enter fullscreen mode Exit fullscreen mode

Once you have the voice_id returned, store it in options.html so the extension uses it by default.


9. Packaging & Testing

  1. Open Chrome → chrome://extensions/.
  2. Enable Developer mode.
  3. Click Load unpacked and select the tts-extension folder.
  4. Open any page, highlight text, and hear it read aloud.
  5. If you want to test the popup, click the extension icon and type something.

Debugging

  • Use chrome://extensions/ → background page → Console to see logs.
  • Inspect the content script from the page’s DevTools → Sources → Content scripts.

10. Next Steps

  • Add voice selection in the popup so users can switch between “alloy”, “fable”, etc.
  • Persist the last spoken text to resume playback.
  • Implement a “Stop” button that calls speechSynthesis.cancel() or pauses the audio element.
  • Add a settings page that fetches the list of available voices from ElevenLabs and populates a dropdown.

11. Wrap‑Up

You now have a fully functional Chrome extension that turns any selected text into speech using ElevenLabs’ neural voices.

Whether you’re building a study aid, a screen‑reader companion, or a voice‑controlled browser, this foundation can be expanded in countless ways.

Ready to bring your words to life?

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

Top comments (0)