Language Detector API: one line of AI that fixes accessibility for multilingual content
Your page says <html lang="en">. Your comments don't.
Every site with user-generated content has this problem, and almost nobody notices it: comments, reviews, chat messages, forum posts. The template is in one language, but people write in their own. For a sighted user that changes nothing. For someone using a screen reader, a Spanish comment inside an English page gets read with English voice and phonetics. "Lo probé en mi proyecto y funciona perfecto" ends up as a syllable soup you have to decode.
The long-standing fix is a lang attribute on the element that switches language. The problem is that you don't know which language each user will write in, and sending every comment to a cloud detection service to find out (with its latency, its API key, and your users' data traveling to a third party) is a lot of cost for one HTML attribute.
Since Chrome 138, you don't need to. The Language Detector API runs a small model on the device: no server, no API key, and the text never leaves the user's machine. And what you do with the result fits, literally, in one line.
This is the first post in a series on Chrome's built-in AI task APIs. The demo is in demos/language-detector-lang-attribute-a11y (the README explains how to run it). Like the previous ones, it has no build step: just ES modules.
How the demo works
It's a fake comment thread on a lang="en" page, with comments in English, Spanish, Portuguese, French, German, and one that only says ok 👍. The flow is:
- Check the availability badge. It shows what
LanguageDetector.availability()returns in your browser, orunsupportedif the API doesn't exist. - Press "Detect languages" (or "Download model & detect", if the model isn't on your device yet). If there's a download, you'll see the progress bar.
- Look at each comment. Each one gets a badge:
lang="es"plus its confidence if the attribute was set, orkept page langif the detector wasn't sure enough. "Ranked results" shows the raw output ofdetect(). - Look at "Resulting markup". It's the HTML read from the DOM after every change: what assistive technology actually gets.
- Move the minimum confidence slider and watch the decisions change without running the model again. Then write a comment in another language: a
MutationObserverannotates it on its own.
Here it is live. It needs desktop Chrome 138 or later; if LanguageDetector isn't available, the demo tells you so and the comments still render:
The problem: a Spanish comment in an English voice
A screen reader doesn't guess the language of each paragraph: it uses whatever the markup declares. If nothing changes it, the whole document is read in the language of <html lang>. That's why WCAG has success criterion 3.1.2 Language of Parts, level AA:
The human language of each passage or phrase in the content can be programmatically determined except for proper names, technical terms, words of indeterminate language, and words or phrases that have become part of the vernacular of the immediately surrounding text.
The Understanding page puts it plainly: declaring the language lets screen readers use that language's pronunciation rules. The standard technique is H58: a lang attribute on the element that changes language.
<html lang="en">
…
<p>Thanks for the detailed write-up!</p>
<p lang="es">Lo probé en mi proyecto y funciona perfecto.</p>
<p lang="pt">Excelente artigo!</p>
</html>With content you write, you add those attributes by hand and you're done. With user content you can't: you don't know ahead of time which language each text comes in. That's where the detector comes in.
Building block 1: detecting the API and its availability
First, find out whether the API exists. Chrome's documentation uses the classic check:
if ('LanguageDetector' in self) {
// The Language Detector API is available.
}Existing doesn't mean you can use it right away. LanguageDetector.availability() returns a promise with one of four values (get started and the explainer):
"unavailable": the device doesn't support it."downloadable": supported, but the model has to be downloaded when you create the detector."downloading": a download is in progress and has to finish."available": you can create the detector right now, with no downloads.
In the demo, lang-detector.js wraps this and adds a fifth state of its own, 'unsupported', for browsers where the API doesn't exist:
export async function getAvailability() {
if (!isLanguageDetectorSupported()) return 'unsupported';
try {
return await LanguageDetector.availability();
} catch {
return 'unavailable';
}
}A few facts worth having at hand. The API is stable since Chrome 138, on desktop only: Chrome's docs say explicitly that the Language Detector and Translator APIs don't work on mobile devices. It doesn't use Gemini Nano: it's an expert model that, according to Google, is very small compared with others, and it may already be on the device because other Chrome features use it. The published hardware requirements (22 GB free, more than 4 GB of VRAM, and so on) are those of the Gemini Nano APIs, like the Prompt API; the docs don't list separate requirements for the Language Detector.
Building block 2: creating the detector (and the download, which needs a click)
LanguageDetector.create() is what downloads the model when needed. It takes a monitor to track progress:
const detector = await LanguageDetector.create({
monitor(m) {
m.addEventListener('downloadprogress', (e) => {
console.log(`Downloaded ${e.loaded * 100}%`);
});
},
});In the offline-first AI post I handled two possible shapes of downloadprogress because it wasn't clear which one would arrive. You don't need that here: the spec fires a ProgressEvent with total fixed at 1, so loaded is always a fraction between 0 and 1. If the download fails, the events stop and create() rejects with a NetworkError.
The catch is user activation. If availability() said "downloadable", create() needs transient activation: a recent click or key press. Without it, the promise rejects with NotAllowedError. (If it said "downloading", it's enough that the user has interacted with the page at some point. If it said "available", nothing is required.) Chrome's docs suggest checking navigator.userActivation.isActive before calling create().
In practice that means one rule: the first call to create() goes inside a click handler, with no earlier await delaying it. In the demo, the detector is shared across the page:
let detectorPromise = null;
export function getLanguageDetector({ onProgress } = {}) {
if (!isLanguageDetectorSupported()) return Promise.resolve(null);
detectorPromise ??= LanguageDetector.create({
monitor(m) {
// `loaded` is a fraction between 0 and 1 (the spec fixes `total` at 1).
m.addEventListener('downloadprogress', (e) => onProgress?.(e.loaded));
},
}).catch((error) => {
detectorPromise = null; // allow a retry, e.g. after a click
throw error;
});
return detectorPromise;
}And the button's handler calls it before anything else. If a NotAllowedError comes back, the demo asks you to press the button again instead of hanging.
One more detail: by default, the API is only available to top-level windows and same-origin iframes (that's why the demo embedded above works). A cross-origin iframe needs it delegated with allow="language-detector". And it isn't available in Web Workers.
Building block 3: detect() and the line that matters
With the detector created, detect(text) returns an array of { detectedLanguage, confidence }, sorted from most to least confident:
const results = await detector.detect('Lo probé en mi proyecto y funciona perfecto.');
// [
// { detectedLanguage: 'es', confidence: … }, // most likely first
// …
// { detectedLanguage: 'und', confidence: … }, // always last
// ]Three details from the explainer worth knowing before you build logic on top:
detectedLanguageis a BCP 47 tag, the same format thelangattribute expects. Nothing to translate.- The last entry is always
"und"(undetermined): the probability that the text isn't in any language the model knows. The array always has at least one entry, even if it's onlyund. - According to the spec, results under 1% are dropped. In practice, don't rely on it: in Chrome 158,
detect('ok 👍')gave me more than sixty entries, nearly all of them below 0.01. Take the top result and move on.
Now, the line. Take the top result and, only if it clears a threshold, copy it onto the element:
export function applyLang(element, results, minConfidence = DEFAULT_MIN_CONFIDENCE) {
const [top] = results;
if (top && top.detectedLanguage !== 'und' && top.confidence >= minConfidence) {
element.lang = top.detectedLanguage; // the one line
return top.detectedLanguage;
}
element.removeAttribute('lang'); // not sure: inherit the page language
return null;
}element.lang = top.detectedLanguage. That's the one line of AI that fixes your accessibility. The rest is deciding when not to run it.
The demo's threshold is 0.7, and that's my call, not the documentation's. The explainer's example uses 0.4 to decide whether to translate a text; for accessibility I'd rather be more conservative, because a wrong lang is worse than none (more on that below). The demo's ok 👍 comment shows why the threshold matters: in my test, the top result was ar-Latn (romanized Arabic) at 0.53, with English second at 0.18. Without a threshold, that "ok" would be read with Arabic phonetics. Chrome's docs also warn that accuracy is low for very short phrases and single words. When not to trust the detector (short texts, Spanglish, code-switching) is enough material for its own post: it's coming later in the series.
Keeping applyLang() separate from detection has another upside: the demo's slider re-applies the decision to the stored results without running the model again.
Building block 4: a helper for all your user content
With that, annotating an element is detect, then apply:
export async function annotateLang(element, detector, { minConfidence = DEFAULT_MIN_CONFIDENCE } = {}) {
const text = element.textContent.trim();
if (!text) return null;
const results = await detector.detect(text);
applyLang(element, results, minConfidence);
return results;
}So you don't have to remember to call it everywhere, the demo marks user content with a data-ugc attribute and lets a MutationObserver handle anything added later (new comments, infinite scroll, chat messages):
export function observeUgc(root, detector, { minConfidence, onResult } = {}) {
const run = async (el) => {
try {
onResult?.(el, await annotateLang(el, detector, { minConfidence }));
} catch (error) {
console.warn('Language detection failed for', el, error);
onResult?.(el, null, error);
}
};
root.querySelectorAll('[data-ugc]').forEach(run);
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (!(node instanceof HTMLElement)) continue;
if (node.matches('[data-ugc]')) run(node);
node.querySelectorAll('[data-ugc]').forEach(run);
}
}
});
observer.observe(root, { childList: true, subtree: true });
return () => observer.disconnect();
}Note where data-ugc goes: on the paragraph with the user's text, not on the whole comment. The author's name, the date, and the buttons belong to your UI and are in the page's language. Put lang on the container and "Reply" and "2 hours ago" get read in a Portuguese voice.
Two more APIs the detector exposes that you don't need here, but should know about:
inputQuotaandmeasureInputUsage(text): if a text exceeds the quota,detect()rejects withQuotaExceededError. For comments I don't worry about it, and to identify a language you don't need to send a whole document anyway: the first few paragraphs are enough.destroy(): unloads the model from memory and rejects anydetect()calls in progress. On a comments page I keep it alive; in a view that unmounts, destroy it on the way out. Bothcreate()anddetect()also accept anAbortControllersignal.
If your use case only needs to recognize certain languages, create() takes expectedInputLanguages (for example ['en', 'es']): it lets the browser download whatever those languages need, and rejects with NotSupportedError if it can't detect them. For open comments, where anyone writes in any language, I don't use it.
Building block 5: in React
In React you don't need the MutationObserver: the component rendering the text already knows when it changes. A hook that returns the detected language, or undefined to inherit:
'use client';
import { useEffect, useState } from 'react';
import { DEFAULT_MIN_CONFIDENCE, getReadyLanguageDetector } from './lang-detector.js';
export function useDetectedLang(text, minConfidence = DEFAULT_MIN_CONFIDENCE) {
const [lang, setLang] = useState();
useEffect(() => {
const controller = new AbortController();
(async () => {
const detector = await getReadyLanguageDetector();
if (!detector || !text.trim()) return setLang(undefined);
const [top] = await detector.detect(text, { signal: controller.signal });
const confident = top.detectedLanguage !== 'und' && top.confidence >= minConfidence;
setLang(confident ? top.detectedLanguage : undefined);
})().catch((error) => {
if (error.name !== 'AbortError') console.warn(error);
});
return () => controller.abort();
}, [text, minConfidence]);
return lang;
}
function Comment({ author, text }) {
const lang = useDetectedLang(text);
return (
<article>
<h3>{author}</h3>
<p lang={lang}>{text}</p>
</article>
);
}getReadyLanguageDetector() is the helper variant that never starts a download: it returns the detector if it already exists or if the model is already on the device, and null otherwise. A hook runs on render, not inside a click, so it can't meet the user activation requirement. If the model isn't there, the first create() has to come from a user gesture somewhere else in the UI (in the demo, the button). And since lang={undefined} makes React skip the attribute, the paragraph inherits the page's language until there's a confident answer.
The AbortController in the cleanup cancels detection if the text changes or the component unmounts, so a stale answer never overwrites a fresh one.
Building block 6: progressive enhancement, and why no lang beats a wrong one
Look at what happens on each failure path:
- The API doesn't exist (Firefox, Safari, Chrome on mobile):
getAvailability()returns'unsupported', nobody callsdetect(), and the comments inheritlang="en". Exactly what you had before. "unavailable",NotAllowedError,NetworkError: same thing. No comment disappears and no rejected promise breaks rendering.- The detector isn't sure:
applyLang()removes the attribute and the element inherits.
That last decision is the important one. A comment without its own lang gets read in the page's voice: mispronounced if it's in another language, sure, but that's the state your site is in today. A comment with a wrong lang is worse: you're telling the screen reader, with full confidence, to use pronunciation rules that don't apply. And it can happen to text that was in the page's language.
For the same reason, never copy und into the attribute. If you really want to declare "unknown language", the HTML standard defines lang="" for that. For comments, I'd rather inherit: if the detector isn't sure, the page's language is the best bet I have.
How to verify it
Seeing the attribute in the DOM is easy: the demo's "Resulting markup" panel reads it live, and DevTools' Elements panel shows it on every <p>. To check the language an element inherits (which is the one that matters), select it in Elements and try this in the console:
$0.matches(':lang(es)'); // true if the element's language (own or inherited) is Spanish
$0.closest('[lang]').lang; // where that language comes fromBut the real test is listening to it. Read the thread with a screen reader before and after pressing the button:
- NVDA (Windows): in the Speech settings, turn on Automatic language switching. Heads-up: with Windows OneCore voices, switching only works if you have the matching language pack installed.
- VoiceOver (macOS): you need a voice installed for each language.
Before the button, Lucía's comment is read with English phonetics. After, with a Spanish voice. That difference is the whole point of this post.
An honest caveat: what this demo doesn't prove
- I tested it in desktop Chrome 158 (macOS), not with every screen reader combination. Whether a reader switches voices depends on it, the browser, and the installed voices. The WCAG Understanding page says as much: assistive technology limitations don't fail the criterion, so what gets audited is the markup.
- The 0.7 threshold is a heuristic, not a Google recommendation. If your content is mostly short (reactions, chat messages), you'll need more than a number. That's what the next post about the detector is for.
- One comment, one language. If someone mixes languages in the same paragraph, the detector splits the confidence among them (the explainer covers this), and most likely none clears the threshold. The demo does the right thing in that case, inherit, but it doesn't fix it.
What I learned building this
- Sometimes the most useful AI is the smallest. You don't need an LLM for this: a stable, on-device language detection model solves a WCAG criterion most sites with user content don't meet.
- The line is trivial; the threshold isn't. Anyone can write
el.lang = top.detectedLanguage. What makes it accessibility instead of a new bug is deciding when not to write it. - User activation shapes your architecture. The first download needs a click, so the design splits in two: create the detector from a gesture, then use it everywhere without downloading anything.
- Real progressive enhancement means "without the API, nothing changes". No errors, no hidden comments. The worst case is the site you already had.
This is the first post in the series on Chrome's built-in AI task APIs. In the next ones we'll look at when not to trust the detector, and bring in more APIs from the family.
To keep exploring
- The official API guide: Language Detector API on Chrome for Developers, plus the overview of all built-in APIs and their status.
- Requirements and user activation: the Get started with built-in AI guide.
- The explainer and the spec: webmachinelearning/translation-api, with the details on
und,expectedInputLanguages, andinputQuota. - WCAG: Understanding 3.1.2 Language of Parts and technique H58.
- The full demo:
demos/language-detector-lang-attribute-a11y. Move the slider, write a comment in your language, and read it with a screen reader.
Does your site have user content in more than one language? I'd love to hear how you're handling it today, or whether you'd even noticed. Let's talk on X/Twitter or LinkedIn.
