language-detector-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLanguage Detector API
Language Detector API
Procedures
操作流程
Step 1: Identify the browser integration surface
- Inspect the workspace for browser entry points, UI handlers, text-input flows, and any existing AI abstraction layer.
- Execute to inventory likely frontend files and existing Language Detector API markers when a Node runtime is available.
node scripts/find-language-detector-targets.mjs . - If a Node runtime is unavailable, inspect the nearest , HTML entry point, and framework bootstrap files manually to identify the browser app boundary.
package.json - If the workspace contains multiple frontend apps, prefer the app that contains the active route, component, or user-requested feature surface.
- If the inventory still leaves multiple plausible frontend targets, stop and ask which app should receive the Language Detector API integration.
- If the project is not a browser web app, stop and explain that this skill does not apply.
Step 2: Confirm API viability and choose the integration shape
- Read before writing code.
references/language-detector-reference.md - Read when the feature needs a session wrapper, download-progress UI, confidence thresholding, or cleanup shape.
references/examples.md - Read when preview flags, browser channels, iframe rules, or environment constraints matter.
references/compatibility.md - Read when support checks, creation, detection, or cleanup fail.
references/troubleshooting.md - Verify that the feature runs in a secure context.
Window - Verify that the current frame is allowed to use the permissions-policy feature.
language-detector - Choose the narrowest session shape that matches the task:
- bare for general language detection
LanguageDetector.create() - when the product depends on a narrower language set or better accuracy for known languages
expectedInputLanguages - when the UI must surface model download progress
monitor
- bare
- If the feature must run in a worker, on the server, or through a cloud-only contract, stop and explain the platform mismatch.
- If the project uses TypeScript, add or preserve narrow typings for the Language Detector API surface used by the feature.
Step 3: Implement a guarded session wrapper
- Read and adapt it to the framework, state model, and file layout in the workspace.
assets/language-detector-session.template.ts - Centralize support checks around ,
globalThis.isSecureContext, and the sameLanguageDetectorshape the feature will use at runtime.expectedInputLanguages - Gate session creation behind using the same create options that will be passed to
LanguageDetector.availability().LanguageDetector.create() - Treat as a capability check, not a guarantee that creation will succeed without download time, policy approval, or user activation.
availability() - Create sessions only after user activation when creation may trigger a model download.
- Use the option during
monitorwhen the product needs download progress.create() - Use for cancelable
AbortController,create(), ordetect()calls, and callmeasureInputUsage()when the session is no longer needed.destroy() - Recreate the session instead of mutating after creation; session options are fixed per instance.
expectedInputLanguages - If the feature lives in a cross-origin iframe, require explicit delegation through .
allow="language-detector"
Step 4: Wire UX and fallback behavior
- Surface distinct states for missing APIs, insecure contexts, blocked frames, downloadable or downloading models, ready sessions, in-flight detection, and aborted work.
- Keep a non-AI fallback for unsupported browsers, blocked frames, or environments that do not meet current preview requirements.
- Treat very short text, single words, and mixed-language snippets as lower-confidence inputs; present confidence-aware UI instead of pretending the top result is always reliable.
- Preserve the full ordered result list when the product needs ranked candidates, and apply any confidence threshold or handling in product logic instead of truncating silently.
und - Treat the trailing result as meaningful uncertainty, not as a defect to remove.
und - Use when quota or input-size budgeting affects the flow.
measureInputUsage() - Do not route translation, summarization, or generic chat tasks through this API; switch to Translator, Writing Assistance APIs, Prompt API, or another approved capability when the task is not language detection.
Step 5: Validate behavior
- Execute to confirm that the intended app boundary and Language Detector API markers still resolve to the edited integration surface.
node scripts/find-language-detector-targets.mjs . - Verify secure-context checks, feature detection, and
LanguageDetectorbehavior before debugging deeper runtime failures.availability() - Test at least one plus
create()flow with representative user text.detect() - If the feature depends on , test both the constrained and unconstrained path or confirm why only one is valid.
expectedInputLanguages - Confirm that cancellation rejects with the expected abort reason and that destroyed sessions are not reused.
- If the target environment depends on preview browser flags or channel-specific behavior, confirm the required browser state from before treating failures as application bugs.
references/compatibility.md - Run the workspace build, typecheck, or tests after editing.
步骤1:确定浏览器集成边界
- 检查工作区中的浏览器入口点、UI处理逻辑、文本输入流程,以及所有现有的AI抽象层。
- 当有可用Node运行环境时,执行来清点可能的前端文件和现有Language Detector API标记。
node scripts/find-language-detector-targets.mjs . - 若没有Node运行环境,手动检查最近的、HTML入口文件和框架启动文件,确定浏览器应用的边界。
package.json - 如果工作区包含多个前端应用,优先选择包含活跃路由、组件或用户需求功能模块的应用。
- 如果清点后仍有多个可能的前端目标,停止操作并询问应该在哪个应用中集成Language Detector API。
- 如果项目不是浏览器网页应用,停止操作并说明本技能不适用该场景。
步骤2:确认API可行性并选择集成形式
- 编写代码前请阅读。
references/language-detector-reference.md - 当功能需要会话封装、下载进度UI、置信度阈值设置或清理逻辑时,请阅读。
references/examples.md - 当需要考虑预览标记、浏览器渠道、iframe规则或环境约束时,请阅读。
references/compatibility.md - 当支持检查、创建、检测或清理操作失败时,请阅读。
references/troubleshooting.md - 确认功能运行在安全的上下文中。
Window - 确认当前框架被允许使用权限策略特性。
language-detector - 选择符合任务需求的最小范围会话形式:
- 通用语言检测使用基础的
LanguageDetector.create() - 当产品依赖更小的语言集合或需要提升已知语言的检测准确率时使用
expectedInputLanguages - 当UI需要展示模型下载进度时使用
monitor
- 通用语言检测使用基础的
- 如果功能必须运行在Worker、服务端或仅通过云协议运行,停止操作并说明平台不匹配。
- 如果项目使用TypeScript,为功能用到的Language Detector API接口添加或保留窄类型定义。
步骤3:实现带防护的会话封装
- 阅读,并适配工作区中的框架、状态模型和文件结构。
assets/language-detector-session.template.ts - 将支持检查逻辑集中在、
globalThis.isSecureContext以及功能运行时会用到的LanguageDetector结构上。expectedInputLanguages - 使用和传入相同的创建参数,将会话创建逻辑前置校验
LanguageDetector.create()的结果。LanguageDetector.availability() - 将视为能力检查,而不是创建操作一定会成功的保证,因为可能存在下载耗时、策略审批或用户激活要求等限制。
availability() - 当创建会话可能触发模型下载时,仅在用户激活后再创建会话。
- 当产品需要下载进度展示时,在调用中传入
create()选项。monitor - 对可取消的、
create()或detect()调用使用measureInputUsage(),并在不再需要会话时调用AbortController。destroy() - 会话创建后不要修改,而是重新创建会话;每个实例的会话选项是固定的。
expectedInputLanguages - 如果功能位于跨域iframe中,需要通过显式授权。
allow="language-detector"
步骤4:对接UX和降级逻辑
- 为以下场景提供清晰的状态展示:API缺失、上下文不安全、框架被拦截、模型可下载/下载中、会话就绪、检测进行中、任务已终止。
- 为不支持的浏览器、被拦截的框架或不符合当前预览要求的环境保留非AI降级方案。
- 将极短文本、单个单词和混合语言片段视为低置信度输入;展示带置信度提示的UI,而不是默认认为返回的第一个结果始终可靠。
- 当产品需要候选结果排序时,保留完整的有序结果列表,在产品逻辑中应用置信度阈值或结果处理,不要静默截断结果。
und - 将末尾的结果视为有意义的不确定性提示,而不是需要移除的缺陷。
und - 当配额或输入大小预算会影响流程时,使用。
measureInputUsage() - 不要将翻译、摘要或通用聊天任务路由到该API;如果任务不是语言检测,请切换到Translator、写作辅助API、Prompt API或其他获批的能力。
步骤5:验证行为
- 执行,确认预期的应用边界和Language Detector API标记仍指向修改后的集成模块。
node scripts/find-language-detector-targets.mjs . - 在调试更深层的运行时故障前,先验证安全上下文检查、特性检测和
LanguageDetector的行为是否正常。availability() - 使用有代表性的用户文本,至少测试一次完整的加
create()流程。detect() - 如果功能依赖,同时测试约束和非约束路径,或确认仅有一种路径有效的原因。
expectedInputLanguages - 确认取消操作会按预期返回终止原因,且已销毁的会话不会被复用。
- 如果目标环境依赖预览浏览器标记或特定渠道的行为,在将故障判定为应用bug前,先对照确认所需的浏览器配置。
references/compatibility.md - 修改完成后运行工作区的构建、类型检查或测试流程。
Error Handling
错误处理
- If is missing, keep a non-AI fallback and confirm secure-context, browser, channel, and flag requirements before changing product logic.
LanguageDetector - If returns
availability()ordownloadable, require user-driven session creation before promising that detection is ready.downloading - If throws
create(), check permissions-policy constraints, missing user activation for downloads, browser policy restrictions, or user rejection.NotAllowedError - If throws
detect(), confirm the document is still fully active and recreate the session after major lifecycle changes if needed.InvalidStateError - If a detection call throws , reduce the input size or measure usage before retrying.
QuotaExceededError - If the feature must run in a worker or server context, stop and explain that the Language Detector API is a window-only browser API.
- 如果不存在,保留非AI降级方案,在修改产品逻辑前先确认安全上下文、浏览器、渠道和标记要求是否满足。
LanguageDetector - 如果返回
availability()或downloadable,在承诺检测能力就绪前,需要用户主动触发会话创建。downloading - 如果抛出
create(),检查权限策略约束、下载所需的用户激活是否缺失、浏览器策略限制或用户拒绝授权。NotAllowedError - 如果抛出
detect(),确认文档仍处于完全活跃状态,若有必要在重大生命周期变更后重新创建会话。InvalidStateError - 如果检测调用抛出,减小输入大小或在重试前统计使用量。
QuotaExceededError - 如果功能必须运行在Worker或服务端上下文,停止操作并说明Language Detector API是仅适用于window上下文的浏览器API。