Building a Browser Extension for Multi-Engine Bilingual Translation: Technical Implementation

    This article explains how to build a browser extension that displays original text and translation side by side using multiple translation engines. It covers a four-layer architecture, engine adapters and routing strategies, automatic language detection trade-offs, BYOK key storage and settings sync boundaries, performance and reading experience optimizations, security and quota governance, and how to compose cloud capabilities. The focus is on adapter abstraction, routing and fallback, key and preference boundaries, rendering performance, and quota management.

    1. Why Web Translation Needs a Plugin-Based Approach

    Built-in browser page translation usually replaces the original text with the translation, so readers lose the original context. In scenarios such as reading academic papers, browsing foreign news, and consulting technical documentation, however, users need a side-by-side reading experience where the original and the translation can be compared. Delivering translation as a browser extension makes it possible to inject a bilingual layer into a page without changing its structure, balancing reading efficiency with semantic verification.

    From an engineering perspective, this type of tool has to solve four problems: connecting to multiple translation services and switching between them at runtime; automatically detecting the source language across more than a hundred languages; defining storage and sync boundaries for keys and preferences; and putting a business model and resource quotas into practice.

    2. Overall Architecture: Four Decoupled Layers

    The extension can be divided into four layers that communicate through message channels, so content scripts never hold network or key capabilities directly.

    • View layer (content script): paragraph detection, bilingual container insertion, text-selection interaction, and immersive styling.
    • Orchestration layer (background Service Worker): request queuing, caching, rate limiting, retries, and engine routing.
    • Adapter layer (engine adapters): reducing differences between providers to a unified interface.
    • Infrastructure layer: key storage, settings sync, quotas, and telemetry.

    A sample definition of the unified adapter interface is shown below (pseudocode that expresses the contract only):

    1. interface TranslateEngine {
    2. id: string;
    3. detect?(text: string): Promise<string>;
    4. translate(req: {
    5. text: string;
    6. from?: string; // if omitted, the engine detects it automatically
    7. to: string;
    8. signal?: AbortSignal;
    9. }): Promise<{ text: string; detected?: string }>;
    10. }

    The value of adapters is that adding a new service only requires implementing this interface and registering it in the routing table; neither the view layer nor the orchestration layer needs to change.

    3. Multi-Engine Integration and Routing Strategy

    A common industry approach is to connect both general machine translation services and large language model (LLM) inference services. The former has low latency and low cost per unit, making it suitable for long text and full pages. The latter is stronger at sentence restructuring, terminology consistency, and contextual coherence, making it suitable for paragraph-level close reading. A three-tier routing design can be used:

    1. Use the general translation service by default to ensure coverage and response speed.
    2. Route selected text or short paragraphs through the LLM path to improve readability.
    3. On failure or when a threshold is exceeded, switch to a lower-priority engine and expose the current engine identifier to the user.

    Routing decisions should be configuration-driven rather than hard-coded:

    1. {
    2. "default": "engine_a",
    3. "rules": [
    4. { "when": "selection", "use": "llm_engine" },
    5. { "when": "text.length > 4000", "use": "engine_a" },
    6. { "when": "error", "fallback": ["engine_b", "engine_a"] }
    7. ]
    8. }

    Note that engines differ significantly in maximum request length, concurrency, and billing. The orchestration layer must therefore split text (at sentence boundaries rather than by fixed-length truncation), cap concurrency, and retry with exponential backoff. Otherwise, full-page translation can easily trigger rate limiting.

    4. Trade-Offs in Automatic Language Detection

    There are two paths to language detection: calling a server-side detection capability or making a lightweight local judgment. Local detection is usually based on character-set and stop-word statistics: Unicode blocks are checked first to determine whether the text contains Japanese kana, Chinese characters, Korean, Cyrillic, and so on; for Latin-script languages, n-grams and stop words are then scored. This approach has low latency and does not require uploading the original text, but its accuracy is limited for short text and minor languages. In practice, a “local pre-judgment plus server-side correction” approach is recommended: the local side produces candidates, and if confidence is below a threshold, the detected field returned by the engine is used to correct the result. The result is cached at the session level to avoid detecting the same paragraph repeatedly.

    5. Drawing the Boundary Between BYOK and Settings Sync

    Extensions for multiple platforms (desktop and mobile) often use the bring-your-own-key (BYOK) model: keys are written only to the local system keychain and are never synced or included in telemetry. Non-sensitive preferences (target language, display mode, bilingual style, and text-selection toggle) are synced across devices through an account system. This split of “keys local, preferences in the cloud” is the balance point between privacy and experience.

    1. // Keys: local secure storage only
    2. await keychain.set('api_key', value);
    3. // Preferences: cloud sync
    4. await sync.set({ targetLang: 'zh', mode: 'bilingual', hover: true });

    If managed quotas are also offered, the key system needs to be extended to a dual channel of “managed token plus user key,” injected uniformly at the request-header level so business code does not need to know the source.

    6. Performance and Reading Experience Optimization

    • Incremental rendering: translate in batches by viewport, use IntersectionObserver for lazy loading, and prioritize the first screen.
    • Layered caching: in-memory LRU plus persistent cache, keyed by “text hash + target language + engine,” which can significantly reduce cost.
    • Structure preservation: use block-level elements as translation units and keep the original nodes when inserting translation containers, avoiding damage to page styles and events.
    • Accessibility: translation containers use semantic tags and reasonable contrast, and support font size and line spacing adjustments.
    • Fault tolerance: a failed paragraph is only marked and does not block the whole page; one-click retry is provided.

    7. Security, Compliance, and Quota Governance

    The extension operates in the context of third-party pages, so it must follow the principle of least privilege: inject scripts only on necessary sites, and narrow network permissions to engine domains. Keys are not written to disk in plaintext or written to logs; telemetry is off by default and text content is desensitized. For quota governance, the free version provides basic capabilities and a daily managed quota, while a subscription model covers the cost of managed inference, forming a sustainable freemium structure.

    8. Combining with Cloud Capabilities

    To build a self-hosted managed translation gateway, you can compose general cloud product categories: place the gateway and rate limiting on a container platform, route tasks and fallback through a message queue, store original and translated text caches in object storage, host keys in a key management service, and connect distributed tracing and metrics to logging and monitoring/alerting services. Baidu AI Cloud offers corresponding capabilities in these general categories, which can be assembled according to the layers above without being tied to a specific interface form.

    9. Summary

    The core competitiveness of a multi-engine bilingual translation extension lies not in “how many services are connected,” but in the adapter-layer abstraction, routing and fallback strategies, the boundary design between keys and preferences, and rendering performance and quota governance. Making these parts solid is what makes the tool reliably usable in long-duration scenarios such as academic reading and news browsing.