> your AI agent picks dependencies from memory; give it dated facts — try starlog.dev ↗ vet your agent's deps ↗ vibe-coding is fine. vibe-importing isn’t. — try starlog.dev ↗ vibe-importing isn’t fine ↗ your agent has never seen your private packages — try starlog.dev ↗ facts for private packages ↗ a linter for the dependencies your AI agent picks — try starlog.dev ↗ a linter for agent deps ↗ whois is redacted, cdns mask the rest — get the real operator — try whoisgeni.us ↗ who really runs that domain ↗ domain attribution that shows its work — full evidence chain — try whoisgeni.us ↗ domain intel w/ evidence ↗

← Back to Articles

Inside Read Aloud: Building Cross-Browser TTS with Fragmented Codebases

[ View on GitHub ]

Inside Read Aloud: Building Cross-Browser TTS with Fragmented Codebases

Hook

Most browser extensions use a unified codebase with conditional compilation. Read Aloud maintains five separate Git branches—one per browser—backporting fixes manually across all of them.

Context

Reading long-form content on the web is exhausting. Documentation, research papers, news articles—the modern web throws tens of thousands of words at developers daily. Screen readers exist for accessibility, but they're designed for navigation, not consumption. Copying text into dedicated TTS apps breaks flow and fails on dynamic content. The Web Speech API landed in browsers around 2014, promising native text-to-speech, but it's buried behind JavaScript APIs that individual sites rarely implement.

Read Aloud bridges this gap as a browser extension that injects TTS capabilities into every page with one click. But the interesting engineering challenge isn't the speech synthesis itself—it's architecting a system that works across Chrome, Firefox, Edge, and Brave despite their fragmented extension APIs, while simultaneously supporting both free browser voices and premium cloud providers (Google Wavenet, Amazon Polly, IBM Watson) without proxying costs. The repository's branch-per-browser strategy reveals the brutal reality of WebExtension compatibility in 2024.

Technical Insight

TTS Abstraction Layer

activate

extracted text

message passing

user settings

persist state

text chunks

audio playback

audio playback

select engine

select engine

User Clicks Extension

Content Script

DOM Parser

Background Worker

TTS Orchestrator

browser.storage

Settings & State

Popup UI

Controls

Web Speech API

Browser Native

Cloud Providers

Wavenet/Polly/Watson

System architecture — auto-generated

The extension's architecture splits into three layers: content scripts for text extraction, a background worker for TTS orchestration, and a popup UI for controls. When you click the Read Aloud icon, a content script injected into the active tab traverses the DOM to extract readable text, filtering out navigation, ads, and boilerplate. This isn't simple document.body.innerText—it implements custom heuristics similar to Readability.js, scoring elements by text density and removing low-signal containers.

The extracted text flows to the background script (or service worker in Manifest V3), where the TTS abstraction layer kicks in. Here's the critical design decision: the extension supports both the Web Speech API (free, built into browsers) and cloud providers (paid, user-supplied API keys). The abstraction looks roughly like this:

class TtsEngine {
  async speak(text, options) {
    throw new Error('Must implement speak()');
  }
  
  async pause() { /* ... */ }
  async resume() { /* ... */ }
  async stop() { /* ... */ }
}

class WebSpeechTts extends TtsEngine {
  async speak(text, options) {
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.voice = options.voice;
    utterance.rate = options.rate;
    window.speechSynthesis.speak(utterance);
  }
}

class GoogleWavenetTts extends TtsEngine {
  constructor(apiKey) {
    super();
    this.apiKey = apiKey;
  }
  
  async speak(text, options) {
    const chunks = this.chunkText(text, 5000); // API limit
    for (const chunk of chunks) {
      const audio = await this.synthesize(chunk, options);
      await this.playAudio(audio);
    }
  }
  
  async synthesize(text, options) {
    const response = await fetch('https://texttospeech.googleapis.com/v1/text:synthesize', {
      method: 'POST',
      headers: { 'X-Goog-Api-Key': this.apiKey },
      body: JSON.stringify({
        input: { text },
        voice: { languageCode: options.lang, name: options.voice },
        audioConfig: { audioEncoding: 'MP3' }
      })
    });
    const { audioContent } = await response.json();
    return this.base64ToAudio(audioContent);
  }
}

This plugin architecture lets users start free with robotic browser voices, then upgrade to neural voices by dropping in their own API credentials. The freemium model works because the code doesn't change—only the engine instance swaps.

But here's where browser fragmentation bites hard. The repository maintains separate branches (master for Chrome, firefox for Firefox, etc.) because WebExtensions aren't actually portable. Firefox still supports Manifest V2 with sync XHR and background pages, while Chrome now requires Manifest V3 with service workers that can't use speechSynthesis APIs (they run in a worker context, not a window). Edge has quirks with the Web Speech API voice selection. Brave needs special permissions for cryptocurrency site injection.

Instead of a unified build system with conditional compilation—if (BROWSER === 'firefox')—Read Aloud manually backports changes across branches. Fix a bug in text extraction on Chrome? You manually cherry-pick to firefox, edge, brave branches. Add a feature? Port it five times. This creates code drift: features land in one branch weeks before others, and regressions slip through because there's no shared test suite validating all platforms.

Text chunking for cloud APIs reveals another pragmatic compromise. Services like Google TTS limit requests to 5,000 characters, so long articles get split. The naive approach splits on sentence boundaries using regex like /[.!?]\s/, but this breaks on "Dr. Smith" or numbered lists. A better implementation would use natural language processing to detect semantic boundaries, but Read Aloud prioritizes simplicity—occasional awkward pauses beat complex dependencies.

Audio playback state persists in the background script using browser.storage.local, so if you navigate away from a page mid-playback, the extension remembers your position. This requires message passing between content scripts and background:

// Content script
browser.runtime.sendMessage({
  action: 'extractText',
  text: extractedText,
  url: window.location.href
});

// Background script
browser.runtime.onMessage.addListener((msg, sender) => {
  if (msg.action === 'extractText') {
    currentPlayback = {
      text: msg.text,
      tabId: sender.tab.id,
      position: 0
    };
    ttsEngine.speak(msg.text);
  }
});

The lack of automated testing means this message passing, TTS provider fallback logic, and text extraction accuracy rely entirely on manual QA. No unit tests for the extraction heuristics. No integration tests for cloud API error handling. No cross-browser smoke tests. For a project with 1,788 stars and real users depending on it, this is a ticking time bomb.

Gotcha

The branch-per-browser strategy will collapse under Manifest V3 migration pressure. Chrome already requires V3; Firefox will eventually follow. Each browser's V3 implementation differs subtly—service worker lifecycle, storage quota policies, dynamic content script injection. Backporting a unified V3 architecture across five branches is nearly impossible without merge conflicts, meaning the maintainer will likely need a painful consolidation rewrite.

Cloud TTS provider integration sounds premium, but the UX is hostile. Users must create Google Cloud or AWS accounts, enable APIs, generate keys, and paste them into the extension settings. Forget seamless trials—you need a credit card and 15 minutes of console navigation before hearing a single neural voice. This kills conversion. A better architecture would proxy requests through the extension's backend with metered free tier and paid subscriptions, but that requires infrastructure costs the open-source project can't sustain.

Text extraction works well on article-style content but fails on web apps. Try it on Gmail, Google Docs, or Notion—you'll get navigation labels, timestamps, and random UI strings mixed into the narration. The heuristics assume static HTML with semantic tags, not single-page apps rendering content dynamically via JavaScript. There's no integration with ARIA landmarks or semantic accessibility hints that would improve extraction quality.

Verdict

Use if: you're consuming long-form articles, documentation, or research papers across diverse websites and want instant TTS without copy-pasting into external apps. The free Web Speech API voices are good enough for quick consumption, and the cloud TTS option exists if you need quality and already have API credentials. It's the best browser-native solution for ad-hoc reading.

Skip if: you're building accessibility features for your own web app (integrate Web Speech API directly instead), need consistent offline playback (the cloud TTS has no audio caching, and browser voices vary by system), require reliable extraction on SPAs or complex layouts (the heuristics assume traditional article HTML), or expect a polished premium experience (the API key management is developer-hostile for non-technical users). Also skip if you're considering contributing—the multi-branch maintenance is a nightmare that will burn you out.