LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Friday, September 22, 2023

Trying Google Translate with Google Apps Script


Introduction

We will create a simple English to Japanese translator using Google Apps Script. 
The application will have a front-end input form and a back-end server that will process the translation results.



Application

We need to create a front-end form that will allow users to enter the English text they want to translate. 




When you enter English that you want to translate to Japanese and click the button, the English is passed to the server side, and the translated Japanese is returned to the front end using LanguageApp.translate.


Source Code

Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('index').setTitle("Title");
}

function returnJapanese(value) {
return LanguageApp.translate(value, "en", "ja");
}


index.html
<!DOCTYPE html>
<html>
<body>
<textarea id="text"></textarea>
<button id="submit">Translate to Japanese</button>
<script>
document.getElementById("submit").onclick = runTranslate;

function runTranslate() {
var value = document.getElementById("text").value;
google.script.run
.withFailureHandler(onFailure)
.withSuccessHandler(onSuccess)
.returnJapanese(value);
}

function onSuccess(result) {
alert(result);
}

function onFailure(e) {
alert([e.message, e.stack]);
}
</script>
</body>
</html>


Tips

LanguageApp.translate(text, sourceLanguage, targetLanguage)

If source language is empty, it will be auto-detected.


Reference

Class LanguageApp
https://developers.google.com/apps-script/reference/language/language-app

Language support
https://cloud.google.com/translate/docs/languages



English
Take your time.


Japanese
ゆっくりしてください。






Latest post

Extracting data from Google Sheets with regular expressions

Introduction Regular expressions are a powerful tool that can be used to extract data from text.  In Google Sheets, regular expressions ca...