Last active
November 19, 2019 09:34
-
-
Save lacikawiz/cb7b2aaf776ba551c79c0a60a4e221a9 to your computer and use it in GitHub Desktop.
Calling Google Translate from JS, no API Key needed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Calling of simple Google API to translate short pieces of text. | |
| Requires no API key :) | |
| WARNING: This call has a severe rate limitation. Frequent calls will result in a temporary block for your IP address for a few hours. | |
| INPUT: | |
| - source language code, eg: "ru" | |
| - target language code, eg: "en" | |
| - text to be translated | |
| OUTPUT: | |
| - a promise that resolves to an array containing the sentences of the translated text. Each sentence in the original text is one item. | |
| Based on Amit Agarwal's article: https://ctrlq.org/code/19909-google-translate-api | |
| */ | |
| function translate(src,tgt,text){ | |
| var url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${src}&tl=${tgt}&dt=t&q=` + encodeURI(text); | |
| return fetch(url).then(x=>x.json()).then(x=>x[0].map(v=>v[0]) ) | |
| } | |
| //############# EXAMPLE ############################################ | |
| translate("ru","en","Привет! Как Дела?").then(v=>console.log(v.join(""))) | |
| /*output: | |
| Hello! How are you? | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment