-
Notifications
You must be signed in to change notification settings - Fork 1
/
content-script.js
374 lines (325 loc) · 11.5 KB
/
content-script.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/**
* Global variables
*/
const panel_container_id = "-web-extension-ondoku-buttons";
const button_group_id = "-web-extension-ondoku-btn-group";
const play_btn_id = "-web-extension-ondoku-btn-play";
const stop_btn_id = "-web-extension-ondoku-btn-stop";
/**
* Send object wanted to inspect to background script to debug.
* Since currently (as of 30th Aug 2016), firefox cannot output log by console.log in content scripts.
*
* @param {*} obj - Something you want to look inside.
*/
function debug(obj){
chrome.runtime.sendMessage(obj, function(res){});
}
/**
* Function to output summerized error by console.error while trying to do speak.
* @param {String} voice
* @param {String} text
* @param {Object} option
* @param {Error} e
*/
function log_error_while_speaking(voice, text, option, e=null){
if(e){
debug("[ondoku] Exception raised while trying to speak" + e);
}
debug("[ondoku] Voice: " + voice);
debug("[ondoku] Text: " + text);
debug("[ondoku] Option: ");
debug(option);
}
/**
* Show play/stop/resume buttons on a web page
*
* @param {Speaker} speaker
*/
function showButtons(speaker){
removeButtons();
let container = $("<div id='" + panel_container_id + "'></div>");
// Define style for buttons element
let style = {};
const location_of_selection = getSelectionLocation();
style["position"] = "absolute";
style["top"] = location_of_selection.top - 40 + window.scrollY;
style["left"] = location_of_selection.left + 0 + window.scrollX;
container.css(style);
let button_group = $("<div class='" + button_group_id + "'></div>");
let btn_group_style = {};
// Add buttons
// Set up play button
const play_btn = setupPlayButton();
button_group.append(play_btn);
container.append(button_group);
// Make the element draggable.
container.draggable();
// Append the element to body of the web page.
container.appendTo('body');
}
/**
* Set up stop button
*/
function setupStopButton(){
const stop_btn = $("<a id='" + stop_btn_id + "'></a>");
const stop_btn_image = $("<img>");
stop_btn_image.attr('src', chrome.extension.getURL("lib/images/stop_voice_48.png"));
stop_btn.append(stop_btn_image);
stop_btn.on('click', function(e){
speaker.cancel();
const new_play_btn = setupPlayButton();
stop_btn.replaceWith(new_play_btn);
});
return stop_btn;
}
/**
* Set up play button
*/
function setupPlayButton(){
const play_btn = $("<a id='" + play_btn_id + "'></a>");
const stop_btn = setupStopButton();
play_btn.on('click', function(e){
speaker.cancel();
speaker.speak(speaker.textSelected(), {
onstart: function(){
play_btn.replaceWith(stop_btn);
},
onend: function(){
speaker.cancel();
const new_play_btn = setupPlayButton();
stop_btn.replaceWith(new_play_btn);
}
});
});
let play_btn_image = $("<img>");
play_btn_image.attr('src', chrome.extension.getURL("lib/images/play_voice_48.png"));
play_btn.append(play_btn_image);
return play_btn;
}
/**
* Remove play/stop/resumes button on current web page.
*/
function removeButtons(){
// Remove button panel whether it exists.
$("#" + panel_container_id).remove();
}
/**
* Get the exact location of selection of a text.
* @returns {ClientRect}
*/
function getSelectionLocation() {
const selection = window.getSelection();
const oRange = selection.getRangeAt(0);
return oRange.getBoundingClientRect();
}
/**
* Speaker class
*/
const Speaker = function(){
if(!responsiveVoice){
debug('responsivevoice.js is not loaded.');
throw false;
}
this.default_voice = 'UK English Female';
this.option = {
pitch: 1,
rate: 1,
volume: 1,
onerror: function(e){
debug("[ondoku] Error while trying to speak: " );
debug(e);
}
};
};
/**
* Setup option
*/
Speaker.prototype.setupOption = function(opt){
$.extend(this.option, opt);
};
/**
* Get (and sanitize if necessary) selected text on web page.
*/
Speaker.prototype.textSelected = function(){
const selection = window.getSelection().toString();
return selection;
};
/**
* Utter voice based on input text
*
* @param {String} text - A text to be spoken.
* @param {Object=} option - Option
*/
Speaker.prototype.speak = function(text, option={}){
this.setupOption(option);
chrome.storage.local.get('auto_detect_language', (data)=>{
if(data.hasOwnProperty('auto_detect_language') && data.auto_detect_language){
guessLanguage.detect(text, (langCode)=>{
chrome.storage.local.get([
"preferable_voice_English",
"preferable_voice_Portuguese",
"preferable_voice_Spanish",
"preferable_voice_Serbo",
"preferable_voice_Romanian"
], (data)=>{
const preferable_voice = {};
if(data.hasOwnProperty("preferable_voice_English")){
preferable_voice['en'] = data["preferable_voice_English"];
}
if(data.hasOwnProperty("preferable_voice_Portuguese")){
preferable_voice['pt'] = data["preferable_voice_Portuguese"];
}
if(data.hasOwnProperty("preferable_voice_Spanish")){
preferable_voice['es'] = data["preferable_voice_Spanish"];
}
if(data.hasOwnProperty("preferable_voice_Serbo")){
preferable_voice['sh'] = data["preferable_voice_Serbo"];
}
if(data.hasOwnProperty("preferable_voice_Romanian")){
preferable_voice['ro'] = data["preferable_voice_Romanian"];
}
const voice = voiceText(langCode, preferable_voice);
// When voice is undefined, try to speak English.
if(voice){
debug("[ondoku] Auto detected voice type for the text: " + voice);
debug('[ondoku] Text to be spoken: "' + text + '"');
debug("[ondoku] Option:");
debug(this.option);
// Utter!
responsiveVoice.cancel();
try{
responsiveVoice.speak(text, voice, this.option);
}
catch(e){
log_error_while_speaking(e, voice, text, this.option);
}
}
else{
debug("[ondoku] Could not detect language of selected text.");
debug("[ondoku] Falling back to default voice setting: " + this.default_voice);
debug('[ondoku] Text to be spoken: "' + text + "'");
debug("[ondoku] Option:");
debug(this.option);
responsiveVoice.cancel();
try{
responsiveVoice.speak(text, this.default_voice, this.option);
}
catch(e){
log_error_while_speaking(e, this.default_voice, text, this.option);
}
}
});
});
}
else{
chrome.storage.local.get('language', (data)=>{
let voice = this.default_voice;
if(data.hasOwnProperty('language') && data.language){
voice = data.language;
}
debug('[ondoku] Text to be spoken: "' + text + '"');
debug("[ondoku] Voice type: " + voice);
debug("[ondoku] Option:");
debug(this.option);
// Utter!
responsiveVoice.cancel();
try{
responsiveVoice.speak(text, voice, this.option);
}
catch(e){
log_error_while_speaking(e, voice, text, this.option);
}
});
}
});
};
/**
* Check whether voice is streaming.
*/
Speaker.prototype.isPlaying = function(){
return responsiveVoice.isPlaying();
};
/**
* Cancel/Pause/Resume speaking voice
*/
Speaker.prototype.cancel = function(){
responsiveVoice.cancel();
};
Speaker.prototype.pause = function(){
responsiveVoice.pause();
};
Speaker.prototype.resume = function(){
responsiveVoice.resume();
};
/**
*
* @type {Speaker}
*/
const speaker = new Speaker();
/**
* @param {Event} e - An event delegated from event listener.
*/
function onMouseUp(e){
// In case extension button is clicked, do nothing. (Click handler is defined in button function)
const buttons = $("#" + panel_container_id);
if(buttons.length > 0 && (buttons.is(e.target) || buttons.has(e.target).length > 0)){
return;
}
// In case voice is already streaming and button is displayed, do nothing.
if(speaker.isPlaying() && buttons.length > 0){
return;
}
// Remove buttons panel whether it exists
removeButtons();
const text = speaker.textSelected();
// If text is not specified and voice is streaming, cancel streaming.
if(!text && speaker.isPlaying()){
speaker.cancel();
return;
}
// If text is empty and voice is not streaming, do nothing.
else if(!text){
return;
}
// If text is not empty and voice is not streaming, speak the text.
else{
// If option for show button is enabled, do it.
chrome.storage.local.get('show_play_buttons', function(data){
// When `show_play_button` setting is enabled, show button and not stream voice for now.
if(data.hasOwnProperty('show_play_buttons') && data.show_play_buttons){
showButtons(speaker);
}
// If the setting is not enabled, stream voice immediately.
else{
speaker.speak(text);
}
});
}
}
// Remove event handler if it is already attached. (Maybe this is useful only in development phase)
$(document).off('mouseup', onMouseUp);
// Setup event for text to speak
chrome.storage.local.get('enabled', function(data){
if(data.hasOwnProperty('enabled') && data.enabled){
$(document).on('mouseup', onMouseUp);
}
});
/**
* Handler of a message incoming from backgroud/popup scripts.
*/
function messageListener(message, sender, sendResponse){
// Anyway, try to remove event handler at first to prevent to steam duplicate voice in the same web page.
$(document).off('mouseup', onMouseUp);
// Handling addon on/off message
if(message.hasOwnProperty('enabled')){
if(message.enabled){
$(document).on('mouseup', onMouseUp);
sendResponse({message: 'Enabled'});
}
else{
sendResponse({message: 'Disabled'});
}
}
return true;
}
chrome.runtime.onMessage.addListener(messageListener);