You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何借助Google Translate API实现网页内容一键动态翻译?

How to Translate All Text in a Page's Body with Google Translate API on Button Click

Let's fix up your approach and get this working smoothly. Here's a step-by-step solution that preserves your page's DOM structure (so you don't lose buttons, styles, or other elements) and correctly handles the translation API call:

Key Fixes & Improvements to Your Original Code

  • Your current code passes an array directly to the API URL, which will cause formatting issues. We'll encode the full text string properly.
  • Replacing the entire body.innerText would wipe out your page's structure—instead, we'll target only text nodes to update content without breaking elements.
  • We'll add a button trigger so the translation runs on user click.

Full Working Code

<!-- Add a button to trigger translation -->
<button id="translateBtn">Translate Page to Spanish</button>

<script>
document.getElementById('translateBtn').addEventListener('click', async () => {
  // Step 1: Extract all text nodes from the body (skip script/style tags)
  const textNodes = [];
  const walker = document.createTreeWalker(
    document.body,
    NodeFilter.SHOW_TEXT,
    {
      acceptNode: node => {
        // Ignore empty text nodes and text inside script/style tags
        if (node.nodeValue.trim() === '') return NodeFilter.FILTER_REJECT;
        const parentTag = node.parentElement.tagName.toLowerCase();
        if (parentTag === 'script' || parentTag === 'style') return NodeFilter.FILTER_REJECT;
        return NodeFilter.FILTER_ACCEPT;
      }
    }
  );

  let node;
  while (node = walker.nextNode()) {
    textNodes.push(node);
  }

  // Step 2: Combine all text into a single string (API handles large text well)
  const fullText = textNodes.map(n => n.nodeValue).join('\n');

  try {
    // Step 3: Call Google Translate API with properly encoded text
    const encodedText = encodeURIComponent(fullText);
    const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=es&dt=t&q=${encodedText}`;
    
    const response = await fetch(url);
    const data = await response.json();

    // Step 4: Parse the translated text (API returns an array of translation chunks)
    const translatedText = data[0].map(chunk => chunk[0]).join('');

    // Step 5: Split translated text back into matching chunks and update text nodes
    // Split by newlines to match our original combined text
    const translatedChunks = translatedText.split('\n');
    textNodes.forEach((node, index) => {
      node.nodeValue = translatedChunks[index] || node.nodeValue;
    });

  } catch (error) {
    console.error('Translation failed:', error);
    alert('Oops, something went wrong with the translation!');
  }
});
</script>

What This Code Does

  • Text Node Extraction: Uses TreeWalker to safely collect only visible text nodes, skipping scripts, styles, and empty whitespace. This keeps your page structure intact.
  • API Request: Properly encodes the text with encodeURIComponent to avoid URL formatting errors.
  • Translation Parsing: The API returns an array of translation segments—we join these into a single string, then split it back to match the original text chunks.
  • Text Replacement: Updates each text node individually, so buttons, images, and other elements stay in place.

Notes

  • Make sure your page is served over HTTPS (most browsers block HTTP requests to Google's API from HTTPS pages).
  • Google's free translate API has rate limits—for production use, consider using their official Cloud Translation API with an API key.

内容的提问来源于stack exchange,提问作者Leo Galindo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:47:28