-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslater.js
43 lines (32 loc) · 1.05 KB
/
translater.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Translater{
constructor(){
if (this.translate === undefined) {
throw new TypeError("Must override translate");
}
}
}
class GoogleTranslater extends Translater{
constructor(){
super();
this.base_url = "https://translate.googleapis.com/translate_a/single";
}
buildRequest(sourceText, sourceLang, targetLang){
return this.base_url + "?"
+ "client=gtx"
+ "&sl=" + sourceLang
+ "&tl=" + targetLang
+ "&dt=t" + "&q=" + encodeURI(sourceText);
}
translate(word, from = "en", to = "ru", callback = function(translation){
console.log(translation);
}){
let request = this.buildRequest(word, from, to);
let xhr = new XMLHttpRequest();
xhr.onload = function(){
let translation = JSON.parse(xhr.responseText)[0][0][0];
callback(translation);
};
xhr.open("GET", request, true); //async
xhr.send();
}
}