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 ext
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:
- Detects selected text on any page.
- Calls a TTS API (we’ll use ElevenLabs – a top‑tier voice synthesis platform).
- 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
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"
}
}
Key points:
-
activeTablets us inject a small content script to read the selection. -
scriptingis required for the newchrome.scripting.executeScriptAPI 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>
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
}
});
Note: The endpoint
/v1/text-to-speech/{voice_id}is the core ElevenLabs API. ReplacevoiceIdwith 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();
}
);
});
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:
- Record a short (30‑60 s) voice sample.
- Upload it to the ElevenLabs dashboard (the affiliate link below takes you straight there).
- Once the model is ready, copy its
voice_idand replaceDEFAULT_VOICEinpopup.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
- Open Chrome →
chrome://extensions/. - Enable Developer mode (top‑right toggle).
- Click Load unpacked and select the
tts-extensionfolder. - 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.localto avoid re‑synthesizing the same sentence. -
Background playback – let the user keep listening while they navigate to other tabs (use the
chrome.audioAPI or a hiddenaudioelement 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
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.