Translator webapp - apps script, javascript and html
Hi friends, In this article we are going to create a webapp that can use to translate text. I have used following code to create this webapp on Google project. To create your webapp, follow the step.
Screenshot of the app
This is html code that I have used in this app.
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top" />
<base target="_top">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
textarea{height:200px;}
</style>
</head>
<body class="w3-lime">
<h3 class="w3-center">Translator webApp Example || AppsScriptLab.</h3>
<div class="w3-row-padding">
<div class="w3-half">
<select id="fromLang" class="w3-select w3-col s4"onchange="translate()">
<option value="">From</option>
<option value="en">English</option>
<option value="hi">Hindi</option>
<option value="ur">Urdu</option>
<option value="pa">Punjabi</option>
<option value="gu">Gujarati</option>
</select>
<textarea class="w3-input w3-white w3-large"id="stxt"
placeholder="Write somthing..."></textarea>
</div>
<div class="w3-half">
<select id="toLang" class="w3-select w3-col s6"onchange="ttranslate()">
<option value="">To</option>
<option value="en">English</option>
<option value="hi">Hindi</option>
<option value="ur">Urdu</option>
<option value="pa">Punjabi</option>
<option value="gu">Gujarati</option>
</select>
<textarea class="w3-input w3-white"id="ttxt"placeholder="Result goes here..."></textarea>
</div>
</div>
<p class="w3-center">
<input type="submit"class="w3-button w3-deep-orange"
value="Translate" onclick="ttranslate()"></p>
<div class="w3-center" id="response"></div>
<script>
function ttranslate(){
var fl = document.getElementById('fromLang');
var sLang= fl.options[fl.selectedIndex].value;
var tl = document.getElementById('toLang');
var tLang= tl.options[tl.selectedIndex].value;
var stxt = document.getElementById('stxt').value;
var resp = document.getElementById('response');
if(sLang ==="" || tLang === ""){
resp.innerHTML ="Please select language!";
}else if(sLang === tLang){
resp.innerHTML ="Please select different language.";
}else if(stxt===""){
resp.innerHTML ="Please write somthing to translate!";
}else{
function onFailure(error){
resp.innerHTML = error;
};
function onSuccess(res){
resp.innerHTML ="";
document.getElementById('ttxt').value = res;
};
resp.innerHTML = "Translating.....";
google.script.run.withFailureHandler(onFailure)
.withSuccessHandler(onSuccess)
.tran(sLang,tLang,stxt);
}
};
</script>
</body>
</html>
To add more languages in your app. click here.
Code.gs
function doGet() {
var x;
x = HtmlService.createTemplateFromFile('index').evaluate();
x.setTitle("Translator webapp");
return x;
}
function tran(sLang,tLang,stxt){
var response = LanguageApp.translate(stxt,sLang,tLang);
return response;
}