ScreenTranslator/translators/google_api.js

38 lines
1.0 KiB
JavaScript
Raw Normal View History

2020-03-21 01:44:46 +07:00
function httpGetAsync(url, callback) {
let xmlHttp = new XMLHttpRequest();
2020-05-25 00:49:19 +07:00
xmlHttp.timeout = 30000; // msecs
2020-03-21 01:44:46 +07:00
xmlHttp.onreadystatechange = function () {
2020-05-25 00:49:19 +07:00
if (xmlHttp.readyState != 4)
return
if (xmlHttp.status == 200)
2020-03-21 01:44:46 +07:00
callback(xmlHttp.responseText);
2020-05-25 00:49:19 +07:00
else
proxy.setFailed(xmlHttp.statusText)
xmlHttp.onreadystatechange = null;
xmlHttp = null;
2020-03-21 01:44:46 +07:00
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
2018-12-25 00:26:47 +07:00
}
2020-03-21 01:44:46 +07:00
function translate(text, from, to) {
console.log('start translate', text, from, to)
2020-04-03 22:38:59 +07:00
let url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=' + to + '&dt=t&q=' + encodeURIComponent(text);
2020-03-21 01:44:46 +07:00
console.log("loading url", url);
httpGetAsync(url, function (response) {
console.log('received', response);
let object = JSON.parse(response);
let result = '';
object[0].forEach(function (element) {
result += element[0] + ' ';
2018-12-25 00:26:47 +07:00
});
2020-03-21 01:44:46 +07:00
proxy.setTranslated(result);
});
}
function init() {
proxy.translate.connect(translate);
2018-12-25 00:26:47 +07:00
}