跳到正文
DEV Community· douzatan·· 27 分鐘前AI 評分50

閲讀外語開發者文件時,避免識別碼和公式標籤遭改寫

Reading Foreign Developer Docs Without Mangling Identifiers or Formula Tags

AI 導讀

瀏覽器整頁翻譯可能改寫外語開發者文件中的命令、JSON 欄位名稱、變數及公式內容,令複製的範例失效。HTML 的 translate="no" 可讓子元素免受翻譯,MathML 和 KaTeX 公式也需保護;Accept-Language 可能令文件伺服器轉到不同語系版本。翻譯前可在 Chrome DevTools 檢查並鎖定未受保護的程式碼及公式節點。

正文

If you ever pasted a shell command after machine-translating a Japanese or German tutorial and watched npm run --watch turn into translated prose keywords, you already know why reading foreign developer docs requires protecting the DOM before translating a single paragraph. Browser built-in page translation replaces text nodes indiscriminately whenever authors omit exclusion attributes, silently breaking flags, JSON field names, and inline variables.

Before reaching for another extension, three DOM behaviors explain why foreign documentation breaks under naive translation:

  • Full-page translators rewrite inside <code> or <kbd> spans whenever a site theme omits the translate="no" HTML global attribute.
  • Inline mathematical expressions rendered with native MathML (<math>) or KaTeX CSS spans contain Text node variables that get converted into dictionary words.
  • Documentation servers checking the HTTP Accept-Language header redirect browser sessions onto older translated trees without signaling that parameters changed upstream.

Why does full-page translation break syntax when reading foreign developer docs?

Most third-party blogs and regional SDK portals leave HTML code and formula elements unprotected when authors author docs quickly in Markdown. Because standard page-replacement engines walk DOM text nodes sequentially, any missing exclusion flag propagates corruption straight into copy-pasted developer examples when reading foreign developer docs.

According to the MDN translate global attribute reference, HTML's enumerated translate attribute accepts only "yes" (or an empty string) and "no". Under the WHATWG HTML DOM specification, putting translate="no" on a parent container places all descendant elements into no-translate mode automatically, while W3C Internationalization translate guide notes that authors can re-enable translation on explanatory child paragraphs with translate="yes". When a blog renders plain <code> blocks without setting translate="no", full-page Chrome replacement translates string literals, boolean constants, and property names alike.

Software developer in a bright brick home office checking foreign technical documentation beside a mug and potted ficus
Keeping explanatory paragraphs directly below unchanged code blocks lets developers scan unfamiliar docs without breaking shell syntax.

Mathematical specs and graphics benchmarks suffer from a less obvious trap. As documented in the MDN MathML documentation, <math> elements render formulas directly inside HTML5 DOM trees using child tags such as <mi>, <mo>, and <mn> instead of static images. Because <mi>x</mi> looks like ordinary character text to poorly filtered DOM walkers, replacing an entire page turns vector symbol names into localized nouns. Worse still, many multilingual portals inspect your browser's Accept-Language header specification on first request and route you directly to a partially translated mirror, hiding the primary English or Japanese wording that matches the code release. Checking response behavior with a quick shell probe shows immediately whether a docs host rewrites paths based on locale negotiation:

curl -sI -H "Accept-Language: en-US,en;q=0.9" https://example-docs.invalid/api

Whenever a documentation portal returns HTTP 302 with a regional Location header or serves different copy based on Vary: Accept-Language, forcing the English or Japanese canonical slug first ensures you inspect the exact parameter names that ship with the library release. Keep one extra server quirk in mind too: some documentation hubs store your selected language in a site cookie after that first Accept-Language redirect, so switching the URL path manually or clearing the locale preference cookie prevents subsequent clicks from bouncing right back onto stale translated pages.

Even HTML parameter tables inside vendor manuals need the same boundary discipline. Documentation generators frequently render object property keys inside <td><code>timeoutMs</code></td> without setting translate="no" on the table cell, and many legacy portals drop <code> wrappers completely around boolean values (true, false, null) or enum constants (READ_COMMITTED). Keeping those literals visibly anchored directly beneath or beside explanatory sentences prevents subtle type bugs from creeping into config files.

Auditing and locking untranslated DOM nodes in Chrome DevTools

Rather than guessing which blocks a documentation site forgot to shield, inspect the page DOM directly before running any translation overlay. You can verify the core filtering rule with Node.js first on representative node metadata, then apply the live DevTools snippet to lock every unprotected code or math container in the active browser tab:

// Verified in Node.js v20: checks which doc elements lack translate="no" protection
const sampleNodes = [
  { tag: "PRE", hasTranslateNo: false, textLen: 184 },
  { tag: "CODE", hasTranslateNo: true, textLen: 19 },
  { tag: "MATH", hasTranslateNo: false, textLen: 24 },
  { tag: "SPAN", cls: "katex", hasTranslateNo: false, textLen: 31 }
];

const unprotected = sampleNodes.filter((n) => !n.hasTranslateNo);
console.log(`Audited nodes: ${sampleNodes.length}, Missing translate="no": ${unprotected.length}`);
console.log(unprotected.map((n) => `<${n.tag.toLowerCase()}> (${n.textLen} chars)`).join(", "));

Running that verification prints exact audit counts cleanly:

Audited nodes: 4, Missing translate="no": 3
<pre> (184 chars), <math> (24 chars), <span> (31 chars)

When opening an unfamiliar Japanese Zenn post, German hardware manual, or older project wiki in Chrome DevTools Console, run a quick in-session audit and patch missing attributes on code and formula subtrees before translating explanatory prose:

// Run in Chrome DevTools Console on an active doc tab before translating paragraphs
(() => {
  const selectors = "pre, code, kbd, samp, var, math, .katex, .MathJax";
  const nodes = [...document.querySelectorAll(selectors)];
  let patched = 0;

  for (const el of nodes) {
    const insideNoTranslate = el.closest('[translate="no"]');
    if (!insideNoTranslate && el.translate !== false) {
      el.setAttribute("translate", "no");
      el.translate = false;
      patched += 1;
    }
  }

  console.log({ totalScanned: nodes.length, newlyProtected: patched });
})();

Notice two practical quirks on real documentation sites after running that patch. First, older Markdown renderers sometimes wrap inline UI keystrokes (<kbd>Ctrl</kbd>) or terminal sample outputs (<samp>ECONNREFUSED</samp>) without explicit translate attributes, so including kbd and samp alongside pre, code, var catches error strings before any translation layer rewrites them. Second, if a Japanese or German library snippet embeds helpful prose comments (// リトライ上限) inside a <pre> fence while keeping code syntax intact, select just the comment line or translate that section separately after scanning the code structure, rather than leaving an entire <pre> unprotected and risking mangled function calls or boolean literals.

Watch also for client-side documentation frameworks built on React, Docusaurus, Nextra, or VuePress. Clicking a sidebar topic inside a single-page application swaps only the main <article> subtree without performing a full document reload, which resets any manual translate="no" attributes applied on the previous route. Whenever you navigate between API endpoints on an SPA documentation portal, re-run the console guard (or run a small session-only MutationObserver on <main> during long audits) before enabling paragraph translation on newly mounted blocks. Once newlyProtected prints zero or finishes patching, every identifier retains its exact ASCII spelling regardless of which explanatory layer renders below the paragraph.

How to read non-English developer docs safely in four steps

Protecting code nodes solves syntax mangling, yet developers still stall on multi-clause specification sentences and polysemous technical verbs (implement, override, dispatch, deprecated). Combine DOM protection with a disciplined four-step reading workflow in desktop Chrome:

  1. Lock the canonical source page first: Check the documentation switcher or request the upstream en or ja path before translating anything. Whenever HTTP Accept-Language redirection pushes you into a localized stub missing new release flags, switch to the primary language tab first so API signatures match live source code.
  2. Layer explanatory paragraphs underneath unchanged originals: Use an extension designed to read foreign-language developer docs in Chrome set to Append layout rather than full-page replacement. Appending the native explanation below each original paragraph preserves heading hierarchy, code identifiers, and line structure side by side.
  3. Verify isolated verbs and technical modifiers inline: When a dense clause slows comprehension (allows you to implement complex features on web pages), double-click the ambiguous verb (implement) on ordinary body text instead of copying the entire paragraph into another tab. Confirm part of speech (verb rather than physical tool noun) and check that features refers to software capabilities within the surrounding sentence.
  4. Re-read the unmodified top paragraph and run a quick scope sanity check: Glance back at the original paragraph alone to verify whether the sentence describes system purpose or installation steps, then confirm every shell flag and unit name directly against raw code snippets before copying into your repo.

Palingo Two Comprehension Checks answers and Troubleshooting Common Issues guidance advising developers to keep API identifiers in original form
Palingo comprehension check answers and Troubleshooting Common Issues card reinforcing keeping API identifiers and syntax in original form.

When choosing extensions for engineering reading, check operational limits up front. Palingo renders webpage double-click popovers and inline paragraph layers through a desktop Chrome extension (its FAQ notes Chrome & Chromium browsers, whereas mobile browsers cannot install extension overlays for live webpage lookup and can only read tutorials or open standalone web tools). Notice also that interactive demo cards shown on documentation guides illustrate workflow steps without calling live remote services. On the account side, Palingo meters AI page translation on managed models using credits rather than raw model tokens (2,000,000 guest credits or 5,000,000 free Google-account credits every 30 days, expiring after 30 days without rollover; Pro sits at $5.99/month for 30M credits and Ultra at $14.99/month for 80M credits), while single-word dictionary lookup runs along a separate service path. Relying on Append only for dense architectural sections while double-clicking isolated terms keeps daily reading well inside free 30-day allowances.

When to keep inline overlays running versus read raw English only

Good tooling accelerates orientation across unfamiliar codebases, yet experienced engineers switch layers deliberately depending on risk:

  • Keep DOM locks plus Append paragraph layers active when scanning Japanese hardware release notes, orienting across unfamiliar open-source issues, auditing non-native product specs, or parsing long explanatory prose around clear code examples.
  • Turn overlays off and verify raw primary syntax directly when copying IAM/security policies, checking deprecation removal dates (deprecated vs removed), validating numerical rate-limit units (ms vs s, MiB vs MB), or inspecting localized pages suspected of lagging behind upstream source repositories.

Setting translate="no" across unprotected code blocks and holding original sentences directly above short explanations turns foreign engineering docs from a copy-paste hazard into reliable primary source material without breaking a single identifier.

Note: Parts of this article were drafted and edited with AI writing assistance; all code snippets and DOM checks were verified locally.

來源:DEV Community · dev.to