forked from muaz-khan/RTCMultiConnection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTranslationHandler.js
executable file
·77 lines (63 loc) · 3.09 KB
/
TranslationHandler.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// TranslationHandler.js
var TranslationHandler = (function() {
function handle(connection) {
connection.autoTranslateText = false;
connection.language = 'en';
connection.googKey = 'AIzaSyCgB5hmFY74WYB-EoWkhr9cAGr6TiTHrEE';
// www.RTCMultiConnection.org/docs/Translator/
connection.Translator = {
TranslateText: function(text, callback) {
// if(location.protocol === 'https:') return callback(text);
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
var sourceText = encodeURIComponent(text); // escape
var randomNumber = 'method' + connection.token();
window[randomNumber] = function(response) {
if (response.data && response.data.translations[0] && callback) {
callback(response.data.translations[0].translatedText);
return;
}
if (response.error && response.error.message === 'Daily Limit Exceeded') {
console.error('Text translation failed. Error message: "Daily Limit Exceeded."');
return;
}
if (response.error) {
console.error(response.error.message);
return;
}
console.error(response);
};
var source = 'https://www.googleapis.com/language/translate/v2?key=' + connection.googKey + '&target=' + (connection.language || 'en-US') + '&callback=window.' + randomNumber + '&q=' + sourceText;
newScript.src = source;
document.getElementsByTagName('head')[0].appendChild(newScript);
},
getListOfLanguages: function(callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
var response = JSON.parse(xhr.responseText);
if (response && response.data && response.data.languages) {
callback(response.data.languages);
return;
}
if (response.error && response.error.message === 'Daily Limit Exceeded') {
console.error('Text translation failed. Error message: "Daily Limit Exceeded."');
return;
}
if (response.error) {
console.error(response.error.message);
return;
}
console.error(response);
}
}
var url = 'https://www.googleapis.com/language/translate/v2/languages?key=' + connection.googKey + '&target=en';
xhr.open('GET', url, true);
xhr.send(null);
}
};
}
return {
handle: handle
};
})();