-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
447 lines (382 loc) · 11.8 KB
/
background.js
File metadata and controls
447 lines (382 loc) · 11.8 KB
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
'use strict';
import browser from "webextension-polyfill";
import Sound from './common/sound';
import { EventSetting } from './common/event';
import { emptyObject, hasAny, getSenderMuted } from './common/utils';
const gSounds = {};
const gEvents = {};
const contentEvents = {}; // cache events specific to content script, example: {'window.cut': [{options: ...}] }
let ports = [];
let hasStarted = false;
let savingChecked = false; // flag for options page, could be set during onStorageChange, to avoid ditto check in options_saving_check
async function init() {
window.addEventListener('unload', destroy, {once: true});
await loadConfig();
if (hasStarted) {
play('runtime.startup');
hasStarted = false;
}
browser.storage.onChanged.addListener(onStorageChange);
browser.runtime.onMessage.addListener(onMessage);
addListeners();
}
function destroy() {
browser.storage.onChanged.removeListener(onStorageChange);
browser.runtime.onMessage.removeListener(onMessage);
removeListeners();
broadcast({type: 'unbind'});
}
function rebindListenersWithCatcher() {
try {
removeListeners();
addListeners();
broadcast({type: 'bind', events: contentEvents});
} catch (error) {
console.error(`Event binding failed`, error);
const errorProps = {};
if (error instanceof Error) {
errorProps['errorName'] = error.name;
errorProps['errorMessage'] = error.message;
}
browser.runtime.sendMessage({
type: 'rebinding_failed',
details: {
reason: 'Rebinding',
...errorProps
}
});
}
}
function onStorageChange(changes, _area) {
if ('sounds' in changes) {
resetSounds(changes.sounds.newValue);
}
if ('events' in changes) {
resetEvents(changes.events.newValue);
rebindListenersWithCatcher();
savingChecked = true;
}
}
function onMessage(msg, sender, respond) {
if (typeof msg.type !== 'string') {
return;
}
switch (msg.type) {
case 'listeners':
if ('action' in msg) {
if (msg.action === 'bind') {
addListeners();
broadcast({type: 'bind', events: contentEvents});
} else {
removeListeners();
broadcast({type: 'unbind'});
}
} else {
removeListeners();
addListeners();
broadcast({type: 'bind', events: contentEvents});
}
break;
case 'options_saving_check':
if (!savingChecked) {
rebindListenersWithCatcher();
}
savingChecked = false;
break;
}
}
function broadcast(...args) {
ports.forEach(port => port.postMessage(...args));
}
async function onPortMessage(msg, port) {
if (typeof msg.type !== 'string') {
return;
}
const eType = msg.event?.type;
const eCtx = msg.event?.ctx;
switch (msg.type) {
case 'content.on':
if (await getSenderMuted(port.sender) === true) {
return;
}
switch (eType) {
case 'cut':
case 'copy':
case 'paste':
play(`window.${eType}`);
break;
case 'compositionstart':
play('window.compositionstart');
break;
case 'enter-fullscreen':
play('doc.fullscreenEnter');
break;
case 'leave-fullscreen':
play('doc.fullscreenLeave');
break;
case 'navigate':
const { navigationType } = eCtx;
let filter = (event) => {
if ('filter_navType' in event.options) {
let validTypes = event.options['filter_navType']['types'];
return validTypes.includes(navigationType);
}
return true;
};
play('navigate', filter);
break;
}
break;
case 'ready':
port.postMessage({type: 'bind', events: contentEvents});
break;
}
}
function onConnect(port) {
ports.push(port);
port.onMessage.addListener(onPortMessage);
port.onDisconnect.addListener((p) => {
if (p.error) {
console.log('Disconnected due to error', p.error.message);
}
let index = ports.indexOf(p);
if (index > -1) {
ports.splice(index, 1);
}
});
}
async function loadConfig() {
return browser.storage.local.get(['sounds', 'events']).then(items => {
if ('sounds' in items) {
resetSounds(items.sounds);
}
if ('events' in items) {
resetEvents(items.events);
}
}, error => {
console.log(error);
});
}
function addListeners() {
let types = Object.keys(gEvents);
const tabGroupAvailable = typeof browser.tabGroups === 'object';
const tabUpdateFilterProps = ['attention', 'pinned'];
if (tabGroupAvailable) {
tabUpdateFilterProps.push('groupId');
}
toggleListener(browser.downloads.onCreated, onDownloadCreated, types.includes('download.new'));
toggleListener(browser.downloads.onChanged, onDownloadChanged, hasAny(['download.completed', 'download.interrupted'], types));
toggleListener(browser.tabs.onCreated, onTabCreated, types.includes('tabs.created'));
toggleListener(browser.tabs.onRemoved, onTabRemoved, types.includes('tabs.removed'));
toggleListener(browser.tabs.onAttached, onTabAttached, types.includes('tabs.attached'));
toggleListener(
browser.tabs.onUpdated,
onTabUpdated,
hasAny(['tabs.attention', 'tabs.pinned', 'tabs.unpinned', 'tabs.group-in', 'tabs.group-out'], types),
{
urls: ['<all_urls>'],
properties: tabUpdateFilterProps
}
);
toggleListener(browser.windows.onCreated, onWindowCreated, hasAny(['windows.created', 'windows.created-private'], types));
toggleListener(browser.windows.onRemoved, onWindowRemoved, types.includes('windows.removed'));
if (tabGroupAvailable) {
toggleListener(browser.tabGroups.onCreated, onTabGroupCreated, types.includes('tabGroups.created'));
toggleListener(browser.tabGroups.onRemoved, onTabGroupRemoved, types.includes('tabGroups.removed'));
toggleListener(browser.tabGroups.onMoved, onTabGroupMoved, types.includes('tabGroups.moved'));
toggleListener(browser.tabGroups.onUpdated, onTabGroupUpdated, types.includes('tabGroups.updated'));
}
if (typeof browser.webNavigation === 'object') {
['onCommitted', 'onHistoryStateUpdated', 'onReferenceFragmentUpdated'].forEach(event => {
toggleListener(browser.webNavigation[event], onBackForward, types.includes('navigation.backForward'));
});
}
if (typeof browser.webRequest === 'object') {
toggleListener(
browser.webRequest.onCompleted,
onRequestCompleted,
types.includes('request.completed'),
{
urls: ['<all_urls>'],
types: ['main_frame', 'sub_frame']
}
);
}
}
function removeListeners() {
browser.downloads.onCreated.removeListener(onDownloadCreated);
browser.downloads.onChanged.removeListener(onDownloadChanged);
browser.tabs.onCreated.removeListener(onTabCreated);
browser.tabs.onRemoved.removeListener(onTabRemoved);
browser.tabs.onAttached.removeListener(onTabAttached);
browser.tabs.onUpdated.removeListener(onTabUpdated);
browser.windows.onCreated.removeListener(onWindowCreated);
browser.windows.onRemoved.removeListener(onWindowRemoved);
if (typeof browser.tabGroups === 'object') {
browser.tabGroups.onCreated.removeListener(onTabGroupCreated);
browser.tabGroups.onRemoved.removeListener(onTabGroupRemoved);
browser.tabGroups.onMoved.removeListener(onTabGroupMoved);
browser.tabGroups.onUpdated.removeListener(onTabGroupUpdated);
}
browser.runtime.onStartup.removeListener(onStartup);
if (typeof browser.webNavigation === 'object') {
['onCommitted', 'onHistoryStateUpdated', 'onReferenceFragmentUpdated'].forEach(event => {
browser.webNavigation[event].removeListener(onBackForward);
});
}
if (typeof browser.webRequest === 'object') {
browser.webRequest.onCompleted.removeListener(onRequestCompleted);
}
}
function resetSounds(configs) {
emptyObject(gSounds);
configs.forEach(cfg => gSounds[cfg.id] = new Sound(cfg));
}
function resetEvents(configs) {
emptyObject(gEvents);
emptyObject(contentEvents);
configs.forEach(cfg => {
let type = cfg.type;
// Backward compatibility, soundIds was once soundId
if (typeof cfg.soundId === 'string' && typeof cfg.soundIds === 'undefined') {
cfg['soundIds'] = [cfg.soundId];
delete cfg.soundId;
}
if (cfg.enabled && cfg.soundIds.length) {
const e = new EventSetting(cfg);
if (!(type in gEvents)) gEvents[type] = [];
gEvents[type].push(e);
if (EventSetting.getTypeDef(type, 'forContent')) {
if (!(type in contentEvents)) contentEvents[type] = [];
contentEvents[type].push({options: e.options});
}
}
});
}
function toggleListener(host, listener, toggle, ...args) {
if (toggle) {
if (!host.hasListener(listener)) {
host.addListener(listener, ...args);
}
} else {
host.removeListener(listener);
}
}
function play(type, filter = () => true) {
let events = gEvents[type] || [];
events.filter(filter).forEach(e => {
let id = e.nextSoundId();
const sound = gSounds[id];
if (sound) {
sound.play();
}
});
}
// Event Handlers {{{
function onStartup() {
hasStarted = true;
}
function onDownloadCreated(item) { // https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/downloads/onCreated
play('download.new');
}
function onDownloadChanged(delta) { // https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/downloads/onChanged
if (delta.state) {
switch (delta.state.current) {
case 'complete':
play('download.completed');
break;
case 'interrupted':
play('download.interrupted');
break;
}
}
if (delta.error) {
let type = delta.error.current;
if (type && !type.startsWith('USER_')) { // don't consider user action as error
play('download.failure');
}
}
}
function onTabCreated(tab) {
play('tabs.created');
}
function onTabRemoved(tabId, info) {
let filter = (event) => {
if ('ignoreWinClose' in event.options) {
if (event.options['ignoreWinClose']['ignore'] === 'ignore' && info.isWindowClosing) {
return false;
}
}
return true;
};
play('tabs.removed', filter);
}
function onTabAttached(tab) {
play('tabs.attached');
}
function onTabUpdated(tabId, changeInfo, tabInfo) {
const keys = Object.keys(changeInfo);
if (keys.includes('attention') && changeInfo['attention']) {
play('tabs.attention');
}
if (keys.includes('pinned')) {
if (changeInfo['pinned']) {
play('tabs.pinned');
} else {
play('tabs.unpinned');
}
}
if (keys.includes('groupId')) {
if (changeInfo['groupId'] === -1) {
play('tabs.group-out');
} else {
play('tabs.group-in');
}
}
}
function onTabGroupCreated(group) {
play('tabGroups.created');
}
function onTabGroupRemoved(group) {
play('tabGroups.removed');
}
function onTabGroupMoved(group) {
play('tabGroups.moved');
}
function onTabGroupUpdated(group) {
play('tabGroups.updated');
}
function onWindowCreated(win) {
if (win.incognito) {
play('windows.created-private');
} else {
play('windows.created');
}
}
function onWindowRemoved(winId) {
play('windows.removed');
}
function onBackForward(details) { // webNavigation: onHistoryStateUpdated, onReferenceFragmentUpdated, onCommitted
if (details.transitionQualifiers.includes('forward_back') && details.tabId > -1) {
browser.tabs.get(details.tabId).then(tab => {
if (tab.mutedInfo.muted !== true) {
play('navigation.backForward');
}
});
}
}
function onRequestCompleted(details) {
let code = (details.statusCode).toString();
let filter = (event) => {
if ('filter_statusCode' in event.options) {
let pattern = event.options['filter_statusCode']['filter'];
return code.match(pattern);
}
return true;
};
play('request.completed', filter);
}
// }}}
window.addEventListener('DOMContentLoaded', init, {once: true});
browser.runtime.onStartup.addListener(onStartup);
browser.runtime.onConnect.addListener(onConnect);