-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathvapi-background.js
1603 lines (1430 loc) · 54.3 KB
/
vapi-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
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
uBlock Origin - a browser extension to block requests.
Copyright (C) 2014-2015 The uBlock Origin authors
Copyright (C) 2014-present Raymond Hill
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
Home: https://github.com/gorhill/uBlock
*/
// For background page
'use strict';
/******************************************************************************/
import webext from './webext.js';
import { ubolog } from './console.js';
/******************************************************************************/
const manifest = browser.runtime.getManifest();
vAPI.cantWebsocket =
browser.webRequest.ResourceType instanceof Object === false ||
browser.webRequest.ResourceType.WEBSOCKET !== 'websocket';
vAPI.canWASM = vAPI.webextFlavor.soup.has('chromium') === false;
if ( vAPI.canWASM === false ) {
const csp = manifest.content_security_policy;
vAPI.canWASM = csp !== undefined && csp.indexOf("'unsafe-eval'") !== -1;
}
vAPI.supportsUserStylesheets = vAPI.webextFlavor.soup.has('user_stylesheet');
/******************************************************************************/
vAPI.app = {
name: manifest.name.replace(/ dev\w+ build/, ''),
version: (( ) => {
let version = manifest.version;
const match = /(\d+\.\d+\.\d+)(?:\.(\d+))?/.exec(version);
if ( match && match[2] ) {
const v = parseInt(match[2], 10);
version = match[1] + (v < 100 ? 'b' + v : 'rc' + (v - 100));
}
return version;
})(),
intFromVersion: function(s) {
const parts = s.match(/(?:^|\.|b|rc)\d+/g);
if ( parts === null ) { return 0; }
let vint = 0;
for ( let i = 0; i < 4; i++ ) {
const pstr = parts[i] || '';
let pint;
if ( pstr === '' ) {
pint = 0;
} else if ( pstr.startsWith('.') || pstr.startsWith('b') ) {
pint = parseInt(pstr.slice(1), 10);
} else if ( pstr.startsWith('rc') ) {
pint = parseInt(pstr.slice(2), 10) + 100;
} else {
pint = parseInt(pstr, 10);
}
vint = vint * 1000 + pint;
}
return vint;
},
restart: function() {
browser.runtime.reload();
},
};
/******************************************************************************/
/******************************************************************************/
vAPI.storage = webext.storage.local;
/******************************************************************************/
/******************************************************************************/
// https://github.com/gorhill/uMatrix/issues/234
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/privacy/network
// https://github.com/gorhill/uBlock/issues/2048
// Do not mess up with existing settings if not assigning them stricter
// values.
vAPI.browserSettings = (( ) => {
// Not all platforms support `browser.privacy`.
const bp = webext.privacy;
if ( bp instanceof Object === false ) { return; }
return {
// https://github.com/uBlockOrigin/uBlock-issues/issues/1723#issuecomment-919913361
canLeakLocalIPAddresses:
vAPI.webextFlavor.soup.has('firefox') &&
vAPI.webextFlavor.soup.has('mobile'),
set: function(details) {
for ( const setting in details ) {
if ( details.hasOwnProperty(setting) === false ) { continue; }
switch ( setting ) {
case 'prefetching':
const enabled = !!details[setting];
if ( enabled ) {
bp.network.networkPredictionEnabled.clear({
scope: 'regular',
});
} else {
bp.network.networkPredictionEnabled.set({
value: false,
scope: 'regular',
});
}
if ( vAPI.prefetching instanceof Function ) {
vAPI.prefetching(enabled);
}
break;
case 'hyperlinkAuditing':
if ( !!details[setting] ) {
bp.websites.hyperlinkAuditingEnabled.clear({
scope: 'regular',
});
} else {
bp.websites.hyperlinkAuditingEnabled.set({
value: false,
scope: 'regular',
});
}
break;
case 'webrtcIPAddress': {
// https://github.com/uBlockOrigin/uBlock-issues/issues/1928
// https://www.reddit.com/r/uBlockOrigin/comments/sl7p74/
// Hypothetical: some browsers _think_ uBO is still using
// the setting possibly based on cached state from the
// past, and making an explicit API call that uBO is not
// using the setting appears to solve those unexpected
// reported occurrences of uBO interfering despite never
// using the API.
const mustEnable = !details[setting];
if ( this.canLeakLocalIPAddresses === false ) {
if ( mustEnable && vAPI.webextFlavor.soup.has('chromium') ) {
bp.network.webRTCIPHandlingPolicy.clear({
scope: 'regular',
});
}
continue;
}
if ( mustEnable ) {
bp.network.webRTCIPHandlingPolicy.set({
value: 'default_public_interface_only',
scope: 'regular'
});
} else {
bp.network.webRTCIPHandlingPolicy.clear({
scope: 'regular',
});
}
break;
}
default:
break;
}
}
}
};
})();
/******************************************************************************/
/******************************************************************************/
vAPI.isBehindTheSceneTabId = function(tabId) {
return tabId < 0;
};
vAPI.unsetTabId = 0;
vAPI.noTabId = -1; // definitely not any existing tab
// To ensure we always use a good tab id
const toTabId = function(tabId) {
return typeof tabId === 'number' && isNaN(tabId) === false
? tabId
: 0;
};
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webNavigation
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs
vAPI.Tabs = class {
constructor() {
browser.webNavigation.onCreatedNavigationTarget.addListener(details => {
this.onCreatedNavigationTargetHandler(details);
});
browser.webNavigation.onCommitted.addListener(details => {
this.onCommittedHandler(details);
});
browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
this.onUpdatedHandler(tabId, changeInfo, tab);
});
browser.tabs.onActivated.addListener(details => {
this.onActivated(details);
});
// https://github.com/uBlockOrigin/uBlock-issues/issues/151
// https://github.com/uBlockOrigin/uBlock-issues/issues/680#issuecomment-515215220
if ( browser.windows instanceof Object ) {
browser.windows.onFocusChanged.addListener(windowId => {
this.onFocusChangedHandler(windowId);
});
}
browser.tabs.onRemoved.addListener((tabId, details) => {
this.onRemovedHandler(tabId, details);
});
}
async executeScript() {
let result;
try {
result = await webext.tabs.executeScript(...arguments);
}
catch(reason) {
}
return Array.isArray(result) ? result : [];
}
async get(tabId) {
if ( tabId === null ) {
return this.getCurrent();
}
if ( tabId <= 0 ) { return null; }
let tab;
try {
tab = await webext.tabs.get(tabId);
}
catch(reason) {
}
return tab instanceof Object ? tab : null;
}
async getCurrent() {
const tabs = await this.query({ active: true, currentWindow: true });
return tabs.length !== 0 ? tabs[0] : null;
}
async insertCSS(tabId, details) {
if ( vAPI.supportsUserStylesheets ) {
details.cssOrigin = 'user';
}
try {
await webext.tabs.insertCSS(...arguments);
}
catch(reason) {
}
}
async query(queryInfo) {
let tabs;
try {
tabs = await webext.tabs.query(queryInfo);
}
catch(reason) {
}
return Array.isArray(tabs) ? tabs : [];
}
async removeCSS(tabId, details) {
if ( vAPI.supportsUserStylesheets ) {
details.cssOrigin = 'user';
}
try {
await webext.tabs.removeCSS(...arguments);
}
catch(reason) {
}
}
// Properties of the details object:
// - url: 'URL', => the address that will be opened
// - index: -1, => undefined: end of the list, -1: following tab,
// or after index
// - active: false, => opens the tab... in background: true,
// foreground: undefined
// - popup: 'popup' => open in a new window
async create(url, details) {
if ( details.active === undefined ) {
details.active = true;
}
const subWrapper = async ( ) => {
const updateDetails = {
url: url,
active: !!details.active
};
// Opening a tab from incognito window won't focus the window
// in which the tab was opened
const focusWindow = tab => {
if ( tab.active && vAPI.windows instanceof Object ) {
vAPI.windows.update(tab.windowId, { focused: true });
}
};
if ( !details.tabId ) {
if ( details.index !== undefined ) {
updateDetails.index = details.index;
}
browser.tabs.create(updateDetails, focusWindow);
return;
}
// update doesn't accept index, must use move
const tab = await vAPI.tabs.update(
toTabId(details.tabId),
updateDetails
);
// if the tab doesn't exist
if ( tab === null ) {
browser.tabs.create(updateDetails, focusWindow);
} else if ( details.index !== undefined ) {
browser.tabs.move(tab.id, { index: details.index });
}
};
// Open in a standalone window
//
// https://github.com/uBlockOrigin/uBlock-issues/issues/168#issuecomment-413038191
// Not all platforms support vAPI.windows.
//
// For some reasons, some platforms do not honor the left,top
// position when specified. I found that further calling
// windows.update again with the same position _may_ help.
if ( details.popup !== undefined && vAPI.windows instanceof Object ) {
const createDetails = {
url: details.url,
type: details.popup,
};
if ( details.box instanceof Object ) {
Object.assign(createDetails, details.box);
}
const win = await vAPI.windows.create(createDetails);
if ( win === null ) { return; }
if ( details.box instanceof Object === false ) { return; }
if (
win.left === details.box.left &&
win.top === details.box.top
) {
return;
}
vAPI.windows.update(win.id, {
left: details.box.left,
top: details.box.top
});
return;
}
if ( details.index !== -1 ) {
subWrapper();
return;
}
const tab = await vAPI.tabs.getCurrent();
if ( tab !== null ) {
details.index = tab.index + 1;
} else {
details.index = undefined;
}
subWrapper();
}
// Properties of the details object:
// - url: 'URL', => the address that will be opened
// - tabId: 1, => the tab is used if set, instead of creating a new one
// - index: -1, => undefined: end of the list, -1: following tab, or
// after index
// - active: false, => opens the tab in background - true and undefined:
// foreground
// - select: true, => if a tab is already opened with that url, then select
// it instead of opening a new one
// - popup: true => open in a new window
async open(details) {
let targetURL = details.url;
if ( typeof targetURL !== 'string' || targetURL === '' ) {
return null;
}
// extension pages
if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
targetURL = vAPI.getURL(targetURL);
}
if ( !details.select ) {
this.create(targetURL, details);
return;
}
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/query#Parameters
// "Note that fragment identifiers are not matched."
// Fragment identifiers ARE matched -- we need to remove the fragment.
const pos = targetURL.indexOf('#');
const targetURLWithoutHash = pos === -1
? targetURL
: targetURL.slice(0, pos);
const tabs = await vAPI.tabs.query({ url: targetURLWithoutHash });
if ( tabs.length === 0 ) {
this.create(targetURL, details);
return;
}
let tab = tabs[0];
const updateDetails = { active: true };
// https://github.com/uBlockOrigin/uBlock-issues/issues/592
if ( tab.url.startsWith(targetURL) === false ) {
updateDetails.url = targetURL;
}
tab = await vAPI.tabs.update(tab.id, updateDetails);
if ( vAPI.windows instanceof Object === false ) { return; }
vAPI.windows.update(tab.windowId, { focused: true });
}
async update() {
let tab;
try {
tab = await webext.tabs.update(...arguments);
}
catch (reason) {
}
return tab instanceof Object ? tab : null;
}
// Replace the URL of a tab. Noop if the tab does not exist.
replace(tabId, url) {
tabId = toTabId(tabId);
if ( tabId === 0 ) { return; }
let targetURL = url;
// extension pages
if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
targetURL = vAPI.getURL(targetURL);
}
vAPI.tabs.update(tabId, { url: targetURL });
}
async remove(tabId) {
tabId = toTabId(tabId);
if ( tabId === 0 ) { return; }
try {
await webext.tabs.remove(tabId);
}
catch (reason) {
}
}
async reload(tabId, bypassCache = false) {
tabId = toTabId(tabId);
if ( tabId === 0 ) { return; }
try {
await webext.tabs.reload(
tabId,
{ bypassCache: bypassCache === true }
);
}
catch (reason) {
}
}
async select(tabId) {
tabId = toTabId(tabId);
if ( tabId === 0 ) { return; }
const tab = await vAPI.tabs.update(tabId, { active: true });
if ( tab === null ) { return; }
if ( vAPI.windows instanceof Object === false ) { return; }
vAPI.windows.update(tab.windowId, { focused: true });
}
// https://forums.lanik.us/viewtopic.php?f=62&t=32826
// Chromium-based browsers: sanitize target URL. I've seen data: URI with
// newline characters in standard fields, possibly as a way of evading
// filters. As per spec, there should be no whitespaces in a data: URI's
// standard fields.
sanitizeURL(url) {
if ( url.startsWith('data:') === false ) { return url; }
const pos = url.indexOf(',');
if ( pos === -1 ) { return url; }
const s = url.slice(0, pos);
if ( s.search(/\s/) === -1 ) { return url; }
return s.replace(/\s+/, '') + url.slice(pos);
}
onCreatedNavigationTargetHandler(details) {
if ( typeof details.url !== 'string' ) {
details.url = '';
}
if ( /^https?:\/\//.test(details.url) === false ) {
details.frameId = 0;
details.url = this.sanitizeURL(details.url);
this.onNavigation(details);
}
this.onCreated(details);
}
onCommittedHandler(details) {
details.url = this.sanitizeURL(details.url);
this.onNavigation(details);
}
onUpdatedHandler(tabId, changeInfo, tab) {
// Ignore uninteresting update events
const { status = '', title = '', url = '' } = changeInfo;
if ( status === '' && title === '' && url === '' ) { return; }
// https://github.com/gorhill/uBlock/issues/3073
// Fall back to `tab.url` when `changeInfo.url` is not set.
if ( url === '' ) {
changeInfo.url = tab && tab.url;
}
if ( changeInfo.url ) {
changeInfo.url = this.sanitizeURL(changeInfo.url);
}
this.onUpdated(tabId, changeInfo, tab);
}
onRemovedHandler(tabId, details) {
this.onClosed(tabId, details);
}
onFocusChangedHandler(windowId) {
if ( windowId === browser.windows.WINDOW_ID_NONE ) { return; }
vAPI.tabs.query({ active: true, windowId }).then(tabs => {
if ( tabs.length === 0 ) { return; }
const tab = tabs[0];
this.onActivated({ tabId: tab.id, windowId: tab.windowId });
});
}
onActivated(/* details */) {
}
onClosed(/* tabId, details */) {
}
onCreated(/* details */) {
}
onNavigation(/* details */) {
}
onUpdated(/* tabId, changeInfo, tab */) {
}
};
/******************************************************************************/
/******************************************************************************/
if ( webext.windows instanceof Object ) {
vAPI.windows = {
get: async function() {
let win;
try {
win = await webext.windows.get(...arguments);
}
catch (reason) {
}
return win instanceof Object ? win : null;
},
create: async function() {
let win;
try {
win = await webext.windows.create(...arguments);
}
catch (reason) {
}
return win instanceof Object ? win : null;
},
update: async function() {
let win;
try {
win = await webext.windows.update(...arguments);
}
catch (reason) {
}
return win instanceof Object ? win : null;
},
};
}
/******************************************************************************/
/******************************************************************************/
if ( webext.browserAction instanceof Object ) {
vAPI.browserAction = {
setTitle: async function() {
try {
await webext.browserAction.setTitle(...arguments);
}
catch (reason) {
}
},
};
// Not supported on Firefox for Android
if ( webext.browserAction.setIcon ) {
vAPI.browserAction.setBadgeTextColor = async function() {
try {
await webext.browserAction.setBadgeTextColor(...arguments);
}
catch (reason) {
}
};
vAPI.browserAction.setBadgeBackgroundColor = async function() {
try {
await webext.browserAction.setBadgeBackgroundColor(...arguments);
}
catch (reason) {
}
};
vAPI.browserAction.setBadgeText = async function() {
try {
await webext.browserAction.setBadgeText(...arguments);
}
catch (reason) {
}
};
vAPI.browserAction.setIcon = async function() {
try {
await webext.browserAction.setIcon(...arguments);
}
catch (reason) {
}
};
}
}
/******************************************************************************/
/******************************************************************************/
// Must read: https://code.google.com/p/chromium/issues/detail?id=410868#c8
// https://github.com/chrisaljoudi/uBlock/issues/19
// https://github.com/chrisaljoudi/uBlock/issues/207
// Since we may be called asynchronously, the tab id may not exist
// anymore, so this ensures it does still exist.
// https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/browserAction#Browser_compatibility
// Firefox for Android does no support browser.browserAction.setIcon().
// Performance: use ImageData for platforms supporting it.
// https://github.com/uBlockOrigin/uBlock-issues/issues/32
// Ensure ImageData for toolbar icon is valid before use.
vAPI.setIcon = (( ) => {
const browserAction = vAPI.browserAction;
const titleTemplate =
browser.runtime.getManifest().browser_action.default_title +
' ({badge})';
const icons = [
{ path: { '16': 'img/icon_16-off.png', '32': 'img/icon_32-off.png' } },
{ path: { '16': 'img/icon_16.png', '32': 'img/icon_32.png' } },
];
(( ) => {
if ( browserAction.setIcon === undefined ) { return; }
// The global badge text and background color.
if ( browserAction.setBadgeBackgroundColor !== undefined ) {
browserAction.setBadgeBackgroundColor({ color: '#666666' });
}
if ( browserAction.setBadgeTextColor !== undefined ) {
browserAction.setBadgeTextColor({ color: '#FFFFFF' });
}
// As of 2018-05, benchmarks show that only Chromium benefits for sure
// from using ImageData.
//
// Chromium creates a new ImageData instance every call to setIcon
// with paths:
// https://cs.chromium.org/chromium/src/extensions/renderer/resources/set_icon.js?l=56&rcl=99be185c25738437ecfa0dafba72a26114196631
//
// Firefox uses an internal cache for each setIcon's paths:
// https://searchfox.org/mozilla-central/rev/5ff2d7683078c96e4b11b8a13674daded935aa44/browser/components/extensions/parent/ext-browserAction.js#631
if ( vAPI.webextFlavor.soup.has('chromium') === false ) { return; }
const imgs = [];
for ( let i = 0; i < icons.length; i++ ) {
const path = icons[i].path;
for ( const key in path ) {
if ( path.hasOwnProperty(key) === false ) { continue; }
imgs.push({ i: i, p: key });
}
}
// https://github.com/uBlockOrigin/uBlock-issues/issues/296
const safeGetImageData = function(ctx, w, h) {
let data;
try {
data = ctx.getImageData(0, 0, w, h);
} catch(ex) {
}
return data;
};
const onLoaded = function() {
for ( const img of imgs ) {
if ( img.r.complete === false ) { return; }
}
const ctx = document.createElement('canvas').getContext('2d');
const iconData = [ null, null ];
for ( const img of imgs ) {
const w = img.r.naturalWidth, h = img.r.naturalHeight;
ctx.width = w; ctx.height = h;
ctx.clearRect(0, 0, w, h);
ctx.drawImage(img.r, 0, 0);
if ( iconData[img.i] === null ) { iconData[img.i] = {}; }
const imgData = safeGetImageData(ctx, w, h);
if (
imgData instanceof Object === false ||
imgData.data instanceof Uint8ClampedArray === false ||
imgData.data[0] !== 0 ||
imgData.data[1] !== 0 ||
imgData.data[2] !== 0 ||
imgData.data[3] !== 0
) {
return;
}
iconData[img.i][img.p] = imgData;
}
for ( let i = 0; i < iconData.length; i++ ) {
if ( iconData[i] ) {
icons[i] = { imageData: iconData[i] };
}
}
};
for ( const img of imgs ) {
img.r = new Image();
img.r.addEventListener('load', onLoaded, { once: true });
img.r.src = icons[img.i].path[img.p];
}
})();
// parts: bit 0 = icon
// bit 1 = badge text
// bit 2 = badge color
// bit 3 = hide badge
return async function(tabId, details) {
tabId = toTabId(tabId);
if ( tabId === 0 ) { return; }
const tab = await vAPI.tabs.get(tabId);
if ( tab === null ) { return; }
const { parts, state, badge, color } = details;
if ( browserAction.setIcon !== undefined ) {
if ( parts === undefined || (parts & 0b0001) !== 0 ) {
browserAction.setIcon(
Object.assign({ tabId: tab.id }, icons[state])
);
}
if ( (parts & 0b0010) !== 0 ) {
browserAction.setBadgeText({
tabId: tab.id,
text: (parts & 0b1000) === 0 ? badge : ''
});
}
if ( (parts & 0b0100) !== 0 ) {
browserAction.setBadgeBackgroundColor({ tabId: tab.id, color });
}
}
// Insert the badge text in the title if:
// - the platform does not support browserAction.setIcon(); OR
// - the rendering of the badge is disabled
if (
browserAction.setTitle !== undefined && (
browserAction.setIcon === undefined || (parts & 0b1000) !== 0
)
) {
browserAction.setTitle({
tabId: tab.id,
title: titleTemplate.replace(
'{badge}',
state === 1 ? (badge !== '' ? badge : '0') : 'off'
)
});
}
if ( vAPI.contextMenu instanceof Object ) {
vAPI.contextMenu.onMustUpdate(tabId);
}
};
})();
browser.browserAction.onClicked.addListener(function(tab) {
vAPI.tabs.open({
select: true,
url: 'popup.html?tabId=' + tab.id + '&responsive=1'
});
});
/******************************************************************************/
/******************************************************************************/
// https://github.com/uBlockOrigin/uBlock-issues/issues/710
// uBO uses only ports to communicate with its auxiliary pages and
// content scripts. Whether a message can trigger a privileged operation is
// decided based on whether the port from which a message is received is
// privileged, which is a status evaluated once, at port connection time.
vAPI.messaging = {
ports: new Map(),
listeners: new Map(),
defaultHandler: null,
PRIVILEGED_URL: vAPI.getURL(''),
NOOPFUNC: function(){},
UNHANDLED: 'vAPI.messaging.notHandled',
listen: function(details) {
this.listeners.set(details.name, {
fn: details.listener,
privileged: details.privileged === true
});
},
onPortDisconnect: function(port) {
this.ports.delete(port.name);
},
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/Port
// port.sender is always present for onConnect() listeners.
onPortConnect: function(port) {
port.onDisconnect.addListener(port =>
this.onPortDisconnect(port)
);
port.onMessage.addListener((request, port) =>
this.onPortMessage(request, port)
);
const portDetails = { port };
const sender = port.sender;
const { tab, url } = sender;
portDetails.frameId = sender.frameId;
portDetails.frameURL = url;
portDetails.privileged = url.startsWith(this.PRIVILEGED_URL);
if ( tab ) {
portDetails.tabId = tab.id;
portDetails.tabURL = tab.url;
}
this.ports.set(port.name, portDetails);
// https://bugzilla.mozilla.org/show_bug.cgi?id=1652925#c24
port.sender = undefined;
},
setup: function(defaultHandler) {
if ( this.defaultHandler !== null ) { return; }
if ( typeof defaultHandler !== 'function' ) {
defaultHandler = function() {
return this.UNHANDLED;
};
}
this.defaultHandler = defaultHandler;
browser.runtime.onConnect.addListener(
port => this.onPortConnect(port)
);
// https://bugzilla.mozilla.org/show_bug.cgi?id=1392067
// Workaround: manually remove ports matching removed tab.
if (
vAPI.webextFlavor.soup.has('firefox') &&
vAPI.webextFlavor.major < 61
) {
browser.tabs.onRemoved.addListener(tabId => {
for ( const { port, tabId: portTabId } of this.ports.values() ) {
if ( portTabId !== tabId ) { continue; }
this.onPortDisconnect(port);
}
});
}
},
broadcast: function(message) {
const messageWrapper = { broadcast: true, msg: message };
for ( const { port } of this.ports.values() ) {
try {
port.postMessage(messageWrapper);
} catch(ex) {
this.onPortDisconnect(port);
}
}
},
onFrameworkMessage: function(request, port, callback) {
const portDetails = this.ports.get(port.name) || {};
const tabId = portDetails.tabId;
const msg = request.msg;
switch ( msg.what ) {
case 'connectionAccepted':
case 'connectionRefused': {
const toPort = this.ports.get(msg.fromToken);
if ( toPort !== undefined ) {
msg.tabId = tabId;
toPort.port.postMessage(request);
} else {
msg.what = 'connectionBroken';
port.postMessage(request);
}
break;
}
case 'connectionRequested':
msg.tabId = tabId;
for ( const { port: toPort } of this.ports.values() ) {
if ( toPort === port ) { continue; }
try {
toPort.postMessage(request);
} catch (ex) {
this.onPortDisconnect(toPort);
}
}
break;
case 'connectionBroken':
case 'connectionCheck':
case 'connectionMessage': {
const toPort = this.ports.get(
port.name === msg.fromToken ? msg.toToken : msg.fromToken
);
if ( toPort !== undefined ) {
msg.tabId = tabId;
toPort.port.postMessage(request);
} else {
msg.what = 'connectionBroken';
port.postMessage(request);
}
break;
}
case 'extendClient':
vAPI.tabs.executeScript(tabId, {
file: '/js/vapi-client-extra.js',
frameId: portDetails.frameId,
}).then(( ) => {
callback();
});
break;
case 'localStorage': {
if ( portDetails.privileged !== true ) { break; }
const args = msg.args || [];
vAPI.localStorage[msg.fn](...args).then(result => {
callback(result);
});
break;
}
case 'userCSS':
if ( tabId === undefined ) { break; }
const promises = [];
if ( msg.add ) {
const details = {
code: undefined,
frameId: portDetails.frameId,
matchAboutBlank: true,
runAt: 'document_start',
};
for ( const cssText of msg.add ) {
details.code = cssText;
promises.push(vAPI.tabs.insertCSS(tabId, details));
}
}
if ( msg.remove ) {
const details = {
code: undefined,
frameId: portDetails.frameId,
matchAboutBlank: true,
};
for ( const cssText of msg.remove ) {
details.code = cssText;
promises.push(vAPI.tabs.removeCSS(tabId, details));
}
}
Promise.all(promises).then(( ) => {
callback();
});
break;
}