如何借助Google Translate API实现网页内容一键动态翻译?
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.innerTextwould 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
TreeWalkerto 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
encodeURIComponentto 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
相关产品推荐
相关产品推荐

