forked from artemave/translate_onhover
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
226 lines (200 loc) · 6.39 KB
/
background.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/* eslint-disable no-console */
import $ from 'jquery'
import Options from './lib/options'
import TransOver from './lib/transover_utils'
import trackEvent from './lib/tracking'
function translate(word, sl, tl, last_translation, onresponse, sendResponse, ga_event_name) {
// Next time url fails:
// - install Google Translate extension: https://chrome.google.com/webstore/detail/google-translate/aapbdbdomjkkjkaonfhkkikfgjllcleb
// - click on extension button to show popup
// - inspect popup to see the requests
const options = {
url: 'https://translate.googleapis.com/translate_a/single?client=gtx&dt=t&dt=bd&dj=1&source=input',
data: {
q: word,
sl: sl,
tl: tl,
},
dataType: 'json',
success: function on_success(data) {
onresponse(data, word, tl, last_translation, sendResponse, ga_event_name)
},
error: function(xhr, status, e) {
trackEvent({
ec: 'error',
ea: 'translate',
el: status,
ev: 1
})
console.log({e: e, xhr: xhr})
}
}
$.ajax(options)
}
function figureOutSlTl(tab_lang) {
const res = {}
if (Options.target_lang() == tab_lang && Options.reverse_lang()) {
res.tl = Options.reverse_lang()
res.sl = Options.target_lang()
console.log('reverse translate into: ', {tl: res.tl, sl: res.sl})
}
else {
res.tl = Options.target_lang()
res.sl = Options.from_lang()
console.log('normal translate into:', {tl: res.tl, sl: res.sl})
}
return res
}
function translationIsTheSameAsInput(sentences, input) {
input = input.replace(/^ *| *$/g, '')
return sentences[0].trans.match(new RegExp(TransOver.regexp_escape(input), 'i'))
}
function on_translation_response(data, word, tl, last_translation, sendResponse) {
let output
const translation = {tl: tl}
console.log('raw_translation: ', data)
if ((!data.dict && !data.sentences) || (!data.dict && translationIsTheSameAsInput(data.sentences, word))) {
translation.succeeded = false
if (Options.do_not_show_oops()) {
output = ''
} else {
output = 'Oops.. No translation found.'
}
} else {
translation.succeeded = true
translation.word = word
output = []
if (data.dict) { // full translation
data.dict.forEach(function(t) {
const translationItem = {pos: t.pos, meanings: t.terms}
output.push(translationItem)
if (t.pos === 'noun' && data.query_inflections) {
for (let i of data.query_inflections) {
if (i.written_form === word && i.features.gender) {
if (i.features.gender === 1)
translationItem.gender = 'm'
if (i.features.gender === 2)
translationItem.gender = 'f'
if (i.features.gender === 3)
translationItem.gender = 'n'
break
}
}
}
})
} else { // single word or sentence(s)
data.sentences.forEach(function(s) {
output.push(s.trans)
})
output = output.join(' ')
}
translation.sl = data.src
}
if (!( output instanceof String)) {
output = JSON.stringify(output)
}
translation.translation = output
$.extend(last_translation, translation)
console.log('response: ', translation)
sendResponse(translation)
}
const last_translation = {}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
const except_urls = Options.except_urls()
switch (request.handler) {
case 'get_last_tat_sl_tl':
console.log('get_last_tat_sl_tl')
sendResponse({
last_tl: localStorage['last_tat_tl'],
last_sl: localStorage['last_tat_sl']
})
break
case 'get_options':
sendResponse({
options: JSON.stringify(
Object.keys(Options).reduce((result, key) => {
result[key] = Options[key]()
return result
}, {})
)
})
break
case 'translate':
console.log('received to translate: ' + request.word)
chrome.tabs.detectLanguage(null, function(tab_lang) {
let sl, tl
// hack: presence of request.tl/sl means this came from popup translate
if (request.tl && request.sl) {
localStorage['last_tat_tl'] = request.tl
localStorage['last_tat_sl'] = request.sl
sl = request.sl
tl = request.tl
} else {
const sltl = figureOutSlTl(tab_lang)
sl = sltl.sl
tl = sltl.tl
}
translate(request.word, sl, tl, last_translation, on_translation_response, sendResponse, Options.translate_by())
})
break
case 'tts':
if (last_translation.succeeded) {
console.log('tts: ' + last_translation.word + ', sl: ' + last_translation.sl)
trackEvent({ec: 'tts', ea: 'play'})
const msg = new SpeechSynthesisUtterance()
msg.lang = last_translation.sl
msg.text = last_translation.word
msg.rate = 0.7
speechSynthesis.speak(msg)
}
sendResponse({})
break
case 'trackEvent':
trackEvent(request.event)
sendResponse({})
break
case 'setIcon':
chrome.browserAction.setIcon({path: request.disabled ? 'to_bw_38.png' : 'to_38.png'})
break
case 'toggle_disable_on_this_page':
if (request.disable_on_this_page) {
if (!except_urls.find(u => u.match(request.current_url))) {
Options.except_urls(
[request.current_url, ...except_urls]
)
}
} else {
if (except_urls.find(u => u.match(request.current_url))) {
Options.except_urls(
except_urls.filter(u => !u.match(request.current_url))
)
}
}
break
default:
console.error('Unknown request', JSON.stringify(request, null, 2))
sendResponse({})
}
// Without this, firefox sends empty async response
// Details: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage
return true
})
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.sendMessage(tab.id, 'open_type_and_translate')
})
chrome.runtime.onInstalled.addListener(function(details) {
if (details.reason == 'install') {
chrome.tabs.create({url: chrome.runtime.getURL('options.html')})
}
})
chrome.commands.onCommand.addListener(function(command) {
switch (command) {
case 'copy-translation-to-clipboard':
chrome.tabs.query({active: true}, ([activeTab]) => {
chrome.tabs.sendMessage(activeTab.id, 'copy-translation-to-clipboard')
})
break
default:
console.log('Unknown command %s', command)
}
})