Cómo traducir texto en un documento de Documentos de Google
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En esta guía de inicio rápido, se crea un complemento del Editor de Documentos de Google que traduce el texto seleccionado en un documento.
Objetivos
Configura la secuencia de comandos.
Ejecuta la secuencia de comandos.
Requisitos previos
Para usar esta muestra, necesitas cumplir con los siguientes requisitos previos:
Una Cuenta de Google (es posible que las cuentas de Google Workspace requieran la aprobación del administrador)
Un navegador web con acceso a Internet
Configura la secuencia de comandos
Crea un documento de Documentos de Google en docs.new.
Haz clic en Extensiones>Apps Script.
Haz clic en Proyecto sin título.
Cámbiale el nombre al proyecto de Apps Script Translate Docs y haz clic en Cambiar nombre.
Junto al archivo Code.gs, haz clic en Más more_vert>Cambiar nombre. Asígnale el nombre translate al archivo.
Haz clic en Agregar un archivo add>HTML. Asígnale el nombre sidebar al archivo.
Reemplaza el contenido de cada archivo por el siguiente código correspondiente y, luego, haz clic en Guardar .
/** * @OnlyCurrentDoc * * The above comment directs Apps Script to limit the scope of file * access for this add-on. It specifies that this add-on will only * attempt to read or modify the files in which the add-on is used, * and not all of the user's files. The authorization request message * presented to users will reflect this limited scope. *//** * Creates a menu entry in the Google Docs UI when the document is opened. * This method is only used by the regular add-on, and is never called by * the mobile add-on version. * * @param {object} e The event parameter for a simple onOpen trigger. To * determine which authorization mode (ScriptApp.AuthMode) the trigger is * running in, inspect e.authMode. */functiononOpen(e){DocumentApp.getUi().createAddonMenu().addItem('Start','showSidebar').addToUi();}/** * Runs when the add-on is installed. * This method is only used by the regular add-on, and is never called by * the mobile add-on version. * * @param {object} e The event parameter for a simple onInstall trigger. To * determine which authorization mode (ScriptApp.AuthMode) the trigger is * running in, inspect e.authMode. (In practice, onInstall triggers always * run in AuthMode.FULL, but onOpen triggers may be AuthMode.LIMITED or * AuthMode.NONE.) */functiononInstall(e){onOpen(e);}/** * Opens a sidebar in the document containing the add-on's user interface. * This method is only used by the regular add-on, and is never called by * the mobile add-on version. */functionshowSidebar(){constui=HtmlService.createHtmlOutputFromFile('sidebar').setTitle('Translate');DocumentApp.getUi().showSidebar(ui);}/** * Gets the text the user has selected. If there is no selection, * this function displays an error message. * * @return {Array.<string>} The selected text. */functiongetSelectedText(){constselection=DocumentApp.getActiveDocument().getSelection();consttext=[];if(selection){constelements=selection.getSelectedElements();for(leti=0;i < elements.length;++i){if(elements[i].isPartial()){constelement=elements[i].getElement().asText();conststartIndex=elements[i].getStartOffset();constendIndex=elements[i].getEndOffsetInclusive();text.push(element.getText().substring(startIndex,endIndex+1));}else{constelement=elements[i].getElement();// Only translate elements that can be edited as text; skip images and// other non-text elements.if(element.editAsText){constelementText=element.asText().getText();// This check is necessary to exclude images, which return a blank// text element.if(elementText){text.push(elementText);}}}}}if(!text.length)thrownewError('Please select some text.');returntext;}/** * Gets the stored user preferences for the origin and destination languages, * if they exist. * This method is only used by the regular add-on, and is never called by * the mobile add-on version. * * @return {Object} The user's origin and destination language preferences, if * they exist. */functiongetPreferences(){constuserProperties=PropertiesService.getUserProperties();return{originLang:userProperties.getProperty('originLang'),destLang:userProperties.getProperty('destLang')};}/** * Gets the user-selected text and translates it from the origin language to the * destination language. The languages are notated by their two-letter short * form. For example, English is 'en', and Spanish is 'es'. The origin language * may be specified as an empty string to indicate that Google Translate should * auto-detect the language. * * @param {string} origin The two-letter short form for the origin language. * @param {string} dest The two-letter short form for the destination language. * @param {boolean} savePrefs Whether to save the origin and destination * language preferences. * @return {Object} Object containing the original text and the result of the * translation. */functiongetTextAndTranslation(origin,dest,savePrefs){if(savePrefs){PropertiesService.getUserProperties().setProperty('originLang',origin).setProperty('destLang',dest);}consttext=getSelectedText().join('\n');return{text:text,translation:translateText(text,origin,dest)};}/** * Replaces the text of the current selection with the provided text, or * inserts text at the current cursor location. (There will always be either * a selection or a cursor.) If multiple elements are selected, only inserts the * translated text in the first element that can contain text and removes the * other elements. * * @param {string} newText The text with which to replace the current selection. */functioninsertText(newText){constselection=DocumentApp.getActiveDocument().getSelection();if(selection){letreplaced=false;constelements=selection.getSelectedElements();if(elements.length===1 && elements[0].getElement().getType()===DocumentApp.ElementType.INLINE_IMAGE){thrownewError('Can\'t insert text into an image.');}for(leti=0;i < elements.length;++i){if(elements[i].isPartial()){constelement=elements[i].getElement().asText();conststartIndex=elements[i].getStartOffset();constendIndex=elements[i].getEndOffsetInclusive();element.deleteText(startIndex,endIndex);if(!replaced){element.insertText(startIndex,newText);replaced=true;}else{// This block handles a selection that ends with a partial element. We// want to copy this partial text to the previous element so we don't// have a line-break before the last partial.constparent=element.getParent();constremainingText=element.getText().substring(endIndex+1);parent.getPreviousSibling().asText().appendText(remainingText);// We cannot remove the last paragraph of a doc. If this is the case,// just remove the text within the last paragraph instead.if(parent.getNextSibling()){parent.removeFromParent();}else{element.removeFromParent();}}}else{constelement=elements[i].getElement();if(!replaced && element.editAsText){// Only translate elements that can be edited as text, removing other// elements.element.clear();element.asText().setText(newText);replaced=true;}else{// We cannot remove the last paragraph of a doc. If this is the case,// just clear the element.if(element.getNextSibling()){element.removeFromParent();}else{element.clear();}}}}}else{constcursor=DocumentApp.getActiveDocument().getCursor();constsurroundingText=cursor.getSurroundingText().getText();constsurroundingTextOffset=cursor.getSurroundingTextOffset();// If the cursor follows or preceds a non-space character, insert a space// between the character and the translation. Otherwise, just insert the// translation.if(surroundingTextOffset > 0){if(surroundingText.charAt(surroundingTextOffset-1)!==' '){newText=' '+newText;}}if(surroundingTextOffset < surroundingText.length){if(surroundingText.charAt(surroundingTextOffset)!==' '){newText+=' ';}}cursor.insertText(newText);}}/** * Given text, translate it from the origin language to the destination * language. The languages are notated by their two-letter short form. For * example, English is 'en', and Spanish is 'es'. The origin language may be * specified as an empty string to indicate that Google Translate should * auto-detect the language. * * @param {string} text text to translate. * @param {string} origin The two-letter short form for the origin language. * @param {string} dest The two-letter short form for the destination language. * @return {string} The result of the translation, or the original text if * origin and dest languages are the same. */functiontranslateText(text,origin,dest){if(origin===dest)returntext;returnLanguageApp.translate(text,origin,dest);}
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-21 (UTC)"],[],["This document guides the creation of a Google Docs add-on for text translation. It involves creating a new Google Docs file and an Apps Script project. You will rename files to `translate` and `sidebar`, and replace their content with provided code. The code defines functions for opening a sidebar, selecting text, translating it, and inserting the translated text back into the document. After reloading, accessing the add-on requires selecting text, choosing languages, clicking 'Translate', and finally, clicking 'Insert'.\n"]]