🚀Publish FREEJoin WriterDock's early community of writers.Start Writing — It's Free

Build a Safe Multilingual React Editor with Chrome's Built-In AI

Suraj Kumar

Suraj Kumar

Founding Writer #1Contributor

November 24, 2026•15 min read

Illustration for "Build a Safe Multilingual React Editor with Chrome's Built-In AI"

Integrating Chrome’s built-in AI capabilities into a React application offers a distinct advantage: privacy-preserving, low-latency text processing without sending user data to external servers. This guide walks you through building a multilingual text editor component that leverages the browser-native Language Detector and Translator APIs. You will learn how to structure a safe user interface that separates language detection from translation, handles asynchronous state correctly, and prevents stale data from overwriting user input.

The core challenge with client-side AI is not just calling the API, but managing the interaction pattern to ensure data integrity. A translation can look polished yet quietly lose critical context, such as specific dates, budget figures, or conditional logic. For instance, a phrase like "Do not confirm the booking until Maya approves" could be translated in a way that preserves the words but loses the crucial conditional aspect. By keeping the source text visible and requiring explicit user acceptance for the translated result, you mitigate the risk of silent data corruption. This approach treats the AI output as a suggestion rather than a command, which is essential for professional web development tools where accuracy and user control are paramount.

Prerequisites and Environment Setup

Before writing any code, ensure your development environment meets the specific requirements for Chrome’s built-in AI APIs. These features are currently supported on desktop Chrome versions. You will need a React project with TypeScript to leverage strict typing, which is highly beneficial when interacting with browser-native APIs that return specific union types and complex objects.

Key requirements include:

  • A modern desktop Chrome browser: These APIs are exposed globally as window.Translator and window.LanguageDetector.
  • TypeScript: Essential for type safety, as the native APIs return specific union types and objects that benefit from clear interface definitions.
  • React’s useEffect cleanup functions: Crucial for managing asynchronous operations and preventing race conditions, especially when dealing with user input that can change rapidly.

It's important to note that these APIs are not universally available across all platforms or browser versions. Their availability depends on factors like installed language packs and the specific desktop environment. Your application must gracefully degrade if these APIs are not exposed, falling back to manual input or standard web-based translation services if necessary.

To ensure TypeScript recognizes the global Translator and LanguageDetector objects, you'll need to add ambient type declarations to your project. Create a declaration file (e.g., src/types/global.d.ts) with content similar to this:

typescript
1// src/types/global.d.ts
2interface LanguageDetectionResult {
3  language: string;
4  confidence: number;
5  isReliable: boolean;
6}
7
8interface LanguageDetector {
9  detect(text: string): Promise<LanguageDetectionResult[]>;
10}
11
12interface TranslatorAvailabilityResult {
13  sourceLanguage: string;
14  targetLanguage: string;
15  available: boolean;
16}
17
18interface TranslatorOptions {
19  sourceLanguage: string;
20  targetLanguage: string;
21  signal?: AbortSignal;
22}
23
24interface TranslatorInstance {
25  translate(text: string, options?: { signal?: AbortSignal }): Promise<string>;
26  destroy(): void;
27}
28
29interface Translator {
30  availability(options: {
31    sourceLanguage: string;
32    targetLanguage: string;
33  }): Promise<TranslatorAvailabilityResult>;
34  create(options: TranslatorOptions): Promise<TranslatorInstance>;
35}
36
37declare global {
38  interface Window {
39    LanguageDetector?: LanguageDetector;
40    Translator?: Translator;
41  }
42  const LanguageDetector: LanguageDetector;
43  const Translator: Translator;
44}

Remember to include this declaration file in your tsconfig.json if it's not automatically picked up.

Step 1: Detecting Language and Checking Availability Separately

A common pitfall is to treat language detection as an implicit, infallible step in the translation pipeline. In reality, detection and translation are distinct operations with different failure modes. A detector might confidently identify "English" in a short message, but that confidence score says nothing about whether the subsequent translation will preserve a conditional deadline like "do not confirm until approval."

For robust applications, you should display the leading language candidates to the user and ask them to confirm the source language before proceeding. This manual confirmation serves two critical purposes: it ensures the correct source is selected, and it provides a fresh user interaction (a "user gesture") which may be required for model preparation in some browser contexts.

First, let's look at how to detect the source language:

typescript
1// src/utils/languageDetection.ts
2interface LanguageDetectionResult {
3  language: string;
4  confidence: number;
5  isReliable: boolean;
6}
7
8export async function detectLanguage(text: string): Promise<LanguageDetectionResult[]> {
9  if (typeof LanguageDetector === "undefined") {
10    console.warn('LanguageDetector API is not available.');
11    return [];
12  }
13  if (!text.trim()) {
14    return [];
15  }
16  try {
17    const results = await LanguageDetector.detect(text);
18    // Sort by confidence to show leading candidates first
19    return results.sort((a, b) => b.confidence - a.confidence);
20  } catch (error) {
21    console.error('Language detection failed:', error);
22    return [];
23  }
24}

This detectLanguage function returns an array of potential languages with their confidence scores. Presenting these to the user allows them to correct any misidentification, especially for short, ambiguous, or mixed-language inputs.

Next, you need to check the availability of the Translator API for a specific language pair. Note that feature detection (typeof Translator !== "undefined") only tells you if the API exists. Availability checking (Translator.availability()) asks a more specific question: whether the specific language pair (e.g., Japanese to French) is supported on this device, potentially requiring local language packs.

Here is a React hook for checking translator availability:

typescript
1// src/hooks/useTranslatorAvailability.ts
2import { useEffect, useState } from 'react';
3
4interface AvailabilityState {
5  status: 'checking' | 'available' | 'unavailable' | 'error';
6  message: string;
7  isAvailable: boolean;
8}
9
10export function useTranslatorAvailability(source: string, target: string): AvailabilityState {
11  const [state, setState] = useState<AvailabilityState>({
12    status: 'checking',
13    message: 'Checking availability...',
14    isAvailable: false,
15  });
16
17  useEffect(() => {
18    // Reset state when source or target changes
19    setState({ status: 'checking', message: 'Checking pair support...', isAvailable: false });
20
21    if (typeof Translator === "undefined") {
22      setState({
23        status: 'unavailable',
24        message: 'Translator API is not exposed in this browser.',
25        isAvailable: false,
26      });
27      return;
28    }
29
30    // Use an AbortController to cancel previous availability checks if language selection changes rapidly
31    const controller = new AbortController();
32    const signal = controller.signal;
33
34    Translator.availability({
35      sourceLanguage: source,
36      targetLanguage: target,
37    }).then((result) => {
38      if (!signal.aborted) { // Check if this effect is still active
39        setState({
40          status: result.available ? 'available' : 'unavailable',
41          message: result.available
42            ? `Translation available for ${result.sourceLanguage} to ${result.targetLanguage}.`
43            : `Translation unavailable for ${result.sourceLanguage} to ${result.targetLanguage}.`,
44          isAvailable: result.available,
45        });
46      }
47    }).catch((error) => {
48      if (!signal.aborted) {
49        console.error('Translator availability check failed:', error);
50        setState({
51          status: 'error',
52          message: 'Availability check failed due to an error.',
53          isAvailable: false,
54        });
55      }
56    });
57
58    return () => {
59      // Cleanup: Abort any pending availability checks
60      controller.abort();
61    };
62  }, [source, target]);
63
64  return state;
65}

This hook runs the probe whenever the language selection changes. The AbortController in the cleanup function is critical. It prevents an older, slower probe from updating the UI state after the user has already selected a new language pair. If the probe times out or fails, the UI should indicate that readiness is unknown, rather than assuming the feature is unsupported.

Step 2: Creating a Safe Translation Adapter

The translation process involves creating a translator instance, sending the text, and then destroying the instance to free up resources. This lifecycle must be managed carefully to avoid memory leaks and to respect the browser’s resource limits. A robust adapter should own the translator instance and release it immediately after use.

A key aspect of a robust adapter function is handling cancellation. If the user changes the text or language while a translation is in progress, the previous request should be aborted. Using an AbortSignal allows you to cancel the underlying network or computation work, preventing unnecessary processing and potential race conditions.

typescript
1// src/utils/translatorAdapter.ts
2export async function translateText(
3  text: string,
4  sourceLanguage: string,
5  targetLanguage: string,
6  signal: AbortSignal
7): Promise<string> {
8  // Throw immediately if the operation has already been aborted
9  signal.throwIfAborted();
10
11  if (!text.trim()) {
12    return '';
13  }
14
15  if (typeof Translator === "undefined") {
16    throw new Error('Translator API is not available.');
17  }
18
19  let translator: TranslatorInstance | null = null;
20  try {
21    // Create the translator instance, passing the signal for cancellation
22    translator = await Translator.create({
23      sourceLanguage,
24      targetLanguage,
25      signal, // Signal can cancel the creation process itself
26    });
27
28    // Translate the text, passing the signal for cancellation
29    const result = await translator.translate(text, { signal });
30    return result;
31  } finally {
32    // Always destroy the translator instance to free resources, regardless of success or failure
33    if (translator) {
34      translator.destroy();
35    }
36  }
37}

Call this function directly from the translation handler triggered by a user click. It's important not to place unrelated asynchronous operations (like fetching configuration data) before calling Translator.create. The browser may require a recent user interaction (a "user gesture") to initialize the model. If you delay the creation, you might lose this transient activation, causing the API to fail or fall back to a slower server-side request, which defeats the purpose of client-side AI.

Step 3: Handling State and Preventing Stale Results

The most significant pitfall in building a multilingual React editor is displaying a translation that corresponds to outdated source text. Imagine a user types "Meeting at 5 PM," starts a translation to Spanish, then immediately changes the text to "Meeting at 6 PM." If the first translation resolves after the second one, the UI will incorrectly show the Spanish for "5 PM" next to the English "6 PM." This leads to confusing and potentially incorrect information being presented to the user.

To prevent this, you need a request identity check. Every translation request should have a unique ID or timestamp. When a response arrives, the component must verify that it matches the current input state before rendering. If the input has changed since the request was initiated, the result should be discarded.

Here is how to structure a React component to handle this safely, integrating the language detection and availability checks:

typescript
1// src/components/MultilingualEditor.tsx
2import React, { useState, useRef, useCallback, useEffect } from 'react';
3import { detectLanguage } from '../utils/languageDetection';
4import { translateText } from '../utils/translatorAdapter';
5import { useTranslatorAvailability } from '../hooks/useTranslatorAvailability';
6
7export function MultilingualEditor() {
8  const [sourceText, setSourceText] = useState('');
9  const [detectedLanguages, setDetectedLanguages] = useState<string[]>([]);
10  const [selectedSourceLanguage, setSelectedSourceLanguage] = useState('en'); // User-confirmed source
11  const [targetLanguage, setTargetLanguage] = useState('es'); // User-selected target
12  const [translation, setTranslation] = useState('');
13  const [isTranslating, setIsTranslating] = useState(false);
14  const [translationError, setTranslationError] = useState<string | null>(null);
15
16  // Use a ref to track the latest translation request ID
17  const currentRequestIdRef = useRef(0);
18  // Use a ref to store the AbortController for the current translation
19  const abortControllerRef = useRef<AbortController | null>(null);
20
21  // Check availability for the selected language pair
22  const { isAvailable, message: availabilityMessage } = useTranslatorAvailability(
23    selectedSourceLanguage,
24    targetLanguage
25  );
26
27  // Effect to detect language as source text changes (with debounce for performance)
28  useEffect(() => {
29    const handler = setTimeout(async () => {
30      if (sourceText.trim()) {
31        const results = await detectLanguage(sourceText);
32        setDetectedLanguages(results.map(r => r.language));
33        // Optionally, pre-select the highest confidence language if reliable
34        if (results.length > 0 && results[0].isReliable) {
35          setSelectedSourceLanguage(results[0].language);
36        }
37      } else {
38        setDetectedLanguages([]);
39      }
40    }, 500); // Debounce for 500ms
41
42    return () => clearTimeout(handler);
43  }, [sourceText]);
44
45  const handleTranslate = useCallback(async () => {
46    if (!sourceText.trim() || isTranslating || !isAvailable) return;
47
48    // Increment request ID to invalidate any previous in-flight requests
49    const requestId = ++currentRequestIdRef.current;
50    setIsTranslating(true);
51    setTranslation(''); // Clear old suggestion immediately
52    setTranslationError(null);
53
54    // Create a new AbortController for this specific request
55    const controller = new AbortController();
56    abortControllerRef.current = controller; // Store it to allow external cancellation
57
58    try {
59      const result = await translateText(
60        sourceText,
61        selectedSourceLanguage,
62        targetLanguage,
63        controller.signal
64      );
65
66      // Only update state if this is still the latest request
67      if (requestId === currentRequestIdRef.current) {
68        setTranslation(result);
69      }
70    } catch (error: any) {
71      // Check if the error was due to abortion or a genuine failure
72      if (error.name !== 'AbortError' && requestId === currentRequestIdRef.current) {
73        console.error('Translation failed:', error);
74        setTranslationError(`Translation failed: ${error.message || 'Unknown error.'}`);
75      }
76    } finally {
77      // Only update loading state if this is still the latest request
78      if (requestId === currentRequestIdRef.current) {
79        setIsTranslating(false);
80        abortControllerRef.current = null; // Clear the controller reference
81      }
82    }
83  }, [sourceText, isTranslating, isAvailable, selectedSourceLanguage, targetLanguage]);
84
85  // Invalidate pending requests when source text changes
86  const handleSourceChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
87    setSourceText(e.target.value);
88    // Incrementing the ref counter invalidates any in-flight requests
89    // This ensures that even if a translation is in progress, its result will be ignored
90    currentRequestIdRef.current++;
91    // Abort any currently running translation
92    abortControllerRef.current?.abort();
93    setTranslation(''); // Clear previous translation suggestion
94    setIsTranslating(false); // Reset translating state
95    setTranslationError(null); // Clear any previous error
96  };
97
98  return (
99    <div className="multilingual-editor-container">
100      <h2>Multilingual Text Editor</h2>
101      <div className="input-section">
102        <label htmlFor="source-text">Source Text:</label>
103        <textarea
104          id="source-text"
105          value={sourceText}
106          onChange={handleSourceChange}
107          placeholder="Enter text to translate..."
108          rows={6}
109        />
110        {detectedLanguages.length > 0 && (
111          <div className="language-detection-info">
112            Detected languages: {detectedLanguages.join(', ')}.
113            <select
114              value={selectedSourceLanguage}
115              onChange={(e) => setSelectedSourceLanguage(e.target.value)}
116              aria-label="Confirm source language"
117            >
118              {detectedLanguages.map(lang => (
119                <option key={lang} value={lang}>{lang}</option>
120              ))}
121            </select>
122          </div>
123        )}
124      </div>
125
126      <div className="controls-section">
127        <label htmlFor="target-language">Translate to:</label>
128        <select
129          id="target-language"
130          value={targetLanguage}
131          onChange={(e) => setTargetLanguage(e.target.value)}
132          aria-label="Select target language"
133        >
134          <option value="es">Spanish</option>
135          <option value="fr">French</option>
136          <option value="de">German</option>
137          {/* Add more target languages as needed */}
138        </select>
139        <button
140          onClick={handleTranslate}
141          disabled={isTranslating || !sourceText.trim() || !isAvailable}
142        >
143          {isTranslating ? 'Translating...' : 'Translate'}
144        </button>
145        {!isAvailable && <p className="availability-warning">{availabilityMessage}</p>}
146      </div>
147
148      {translationError && <p className="error-message">{translationError}</p>}
149
150      {translation && (
151        <div className="translation-section">
152          <h3>Translation Suggestion:</h3>
153          <p className="translation-output">{translation}</p>
154          <button onClick={() => navigator.clipboard.writeText(translation)}>
155            Accept & Copy
156          </button>
157          {/* Add more actions like "Insert into document" if applicable */}
158        </div>
159      )}
160    </div>
161  );
162}

The currentRequestIdRef acts as a version counter. Any time the source text changes, the counter increments. When a translation resolves, it checks if its own ID matches the current counter. If they don’t match, the result is discarded. This ensures that a late-arriving response never overwrites the state based on newer input. Additionally, the abortControllerRef allows immediate cancellation of an ongoing translation when the source text changes, improving responsiveness.

Step 4: User Acceptance and Data Integrity

Rendering the translation as plain text in React is safe from cross-site scripting (XSS) attacks, but it is not inherently safe from user error or data integrity issues. The translation should always be displayed as a suggestion, not automatically inserted into the main document or used as a definitive replacement. Provide a separate "Accept" or "Copy" button, giving the user explicit control.

This separation is crucial for maintaining data integrity. If the user edits the source text after seeing a translation, the displayed translation immediately becomes stale. If the user were then to click an "Accept" button that automatically applied the translation, they might inadvertently be applying a translation of the old text to their current document. By requiring an explicit action and invalidating the suggestion whenever the source changes, you force the user to re-translate if the input has been modified.

Furthermore, transparency is key. Do not silently turn a local translation action into a server request if the local API is unavailable. If the browser's native API is not exposed or the specific language pair is unsupported, inform the user clearly. Do not hide the fallback mechanism or present a server-side translation as if it were a client-side one. This transparency builds trust, especially when handling sensitive business data like contracts, event briefs, or critical communications.

Common Errors and Pitfalls

When working with browser-native AI APIs, developers often encounter specific challenges:

  1. Confusing Feature Detection with Availability: Checking typeof Translator !== "undefined" only tells you if the API object exists in the global scope. It does not tell you if the specific language pair (e.g., Japanese to French) is supported on the user’s device, which might require installed language packs. Always call Translator.availability() for a definitive answer regarding a specific translation task.
  2. Ignoring Abort Signals: If you do not pass an AbortSignal to Translator.create and translator.translate, you cannot reliably cancel a request. This leads to race conditions where old, stale results can overwrite newer ones, or where the browser continues to perform computationally intensive work even after the user has moved on or changed their input.
  3. Assuming Synchronous Completion: Translation is an asynchronous operation and may take a noticeable amount of time, especially on the first run when the underlying model is being prepared or loaded. Always show a loading state (isTranslating) and avoid blocking the UI. Failing to do so can lead to a frozen or unresponsive user experience.
  4. Treating Detection Confidence as Translation Quality: A high-confidence language detection result (e.g., isReliable: true) only indicates that the input language was identified with high certainty. It does not guarantee a high-quality or contextually accurate translation. The detector identifies the input language; it does not validate the output's semantic integrity.
  5. Lack of Resource Management: Forgetting to call translator.destroy() after a translation is complete can lead to memory leaks and unnecessary resource consumption in the browser, potentially impacting overall application performance and stability. Always ensure destroy() is called in a finally block.

Key Takeaways

  • Separate language detection from translation: Allow the user to confirm the source language to ensure accuracy, especially for ambiguous inputs, and to provide a fresh user gesture for API activation.
  • Always check Translator.availability(): Verify support for the specific language pair, not just the API's existence, to provide accurate user feedback and handle unsupported scenarios gracefully.
  • Use request identity checks: Implement mechanisms like ref counters and AbortController to discard stale translation results when the source text changes, preventing data corruption and improving responsiveness.
  • Require explicit user acceptance: Display translations as suggestions and provide a separate "Accept" or "Copy" action. Never automatically insert translated content to maintain data integrity and user control.
  • Handle errors gracefully: Distinguish clearly between "API not exposed," "Language pair not supported," and "Transient error" to provide helpful feedback to the user.
  • Manage resources: Always call translator.destroy() to release browser resources after a translation operation.

FAQ

Is Chrome's built-in AI available on mobile browsers? No, the current documentation and implementation details specify that these APIs are primarily available on desktop Chrome. Mobile support is not guaranteed and may vary by platform and version. Developers should verify availability on target devices.

Can I use these APIs for real-time translation as the user types? It is generally not recommended to trigger translation on every keystroke. Translation involves significant computation and resource usage. Doing so will likely overwhelm the browser, consume excessive power, and result in a poor user experience. A debounced input (as shown in the example) or an explicit button click is a more appropriate interaction model.

What happens if the user deletes a language pack required for translation? The Translator.availability() check will return a negative result for language pairs that depend on the missing pack. Your application should detect this change and disable the translation button or show an informative error message to the user.

Does this work with offline mode? Yes, that is one of the primary benefits of Chrome's built-in AI. Once the necessary models and language packs are prepared and installed locally, translation can occur without an active internet connection, provided the required resources are available on the device.

About the Author

Suraj Kumar

Suraj Kumar

@surajkumar

Founding Writer #1Contributor

Suraj Kumar is a writer, entrepreneur, and the CEO and founder of this website, sharing simple and practical insights on business, creativity, and personal growth. With experience building digital projects, they enjoy helping others learn, grow, and succeed online.

Read Next

More articles you might enjoy

View all articles
0