-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathvapi-background.js
3630 lines (3113 loc) · 117 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-2106 The uBlock Origin authors
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
*/
/* jshint esnext: true, bitwise: false */
/* global punycode */
// For background page
'use strict';
/******************************************************************************/
(function() {
/******************************************************************************/
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
const {Services} = Cu.import('resource://gre/modules/Services.jsm', null);
/******************************************************************************/
var vAPI = self.vAPI = self.vAPI || {};
vAPI.firefox = true;
vAPI.fennec = Services.appinfo.ID === '{aa3c5121-dab2-40e2-81ca-7ea25febc110}';
vAPI.thunderbird = Services.appinfo.ID === '{3550f703-e582-4d05-9a08-453d09bdfdc6}';
if ( vAPI.fennec ) {
vAPI.battery = true;
}
/******************************************************************************/
var deferUntil = function(testFn, mainFn, details) {
if ( typeof details !== 'object' ) {
details = {};
}
var now = 0;
var next = details.next || 200;
var until = details.until || 2000;
var check = function() {
if ( testFn() === true || now >= until ) {
mainFn();
return;
}
now += next;
vAPI.setTimeout(check, next);
};
if ( 'sync' in details && details.sync === true ) {
check();
} else {
vAPI.setTimeout(check, 1);
}
};
/******************************************************************************/
vAPI.app = {
name: 'uBlock Origin',
version: location.hash.slice(1)
};
/******************************************************************************/
vAPI.app.restart = function() {
// Listening in bootstrap.js
Cc['@mozilla.org/childprocessmessagemanager;1']
.getService(Ci.nsIMessageSender)
.sendAsyncMessage(location.host + '-restart');
};
/******************************************************************************/
// Set default preferences for user to find in about:config
vAPI.localStorage.setDefaultBool('forceLegacyToolbarButton', false);
/******************************************************************************/
// List of things that needs to be destroyed when disabling the extension
// Only functions should be added to it
var cleanupTasks = [];
// This must be updated manually, every time a new task is added/removed
var expectedNumberOfCleanups = 9;
window.addEventListener('unload', function() {
if ( typeof vAPI.app.onShutdown === 'function' ) {
vAPI.app.onShutdown();
}
// IMPORTANT: cleanup tasks must be executed using LIFO order.
var i = cleanupTasks.length;
while ( i-- ) {
cleanupTasks[i]();
}
if ( cleanupTasks.length < expectedNumberOfCleanups ) {
console.error(
'uBlock> Cleanup tasks performed: %s (out of %s)',
cleanupTasks.length,
expectedNumberOfCleanups
);
}
// frameModule needs to be cleared too
var frameModuleURL = vAPI.getURL('frameModule.js');
var frameModule = {};
// https://github.com/gorhill/uBlock/issues/1004
// For whatever reason, `Cu.import` can throw -- at least this was
// reported as happening for Pale Moon 25.8.
try {
Cu.import(frameModuleURL, frameModule);
frameModule.contentObserver.unregister();
Cu.unload(frameModuleURL);
} catch (ex) {
}
});
/******************************************************************************/
// For now, only booleans.
vAPI.browserSettings = {
originalValues: {},
rememberOriginalValue: function(path, setting) {
var key = path + '.' + setting;
if ( this.originalValues.hasOwnProperty(key) ) {
return;
}
var hasUserValue;
var branch = Services.prefs.getBranch(path + '.');
try {
hasUserValue = branch.prefHasUserValue(setting);
} catch (ex) {
}
if ( hasUserValue !== undefined ) {
this.originalValues[key] = hasUserValue ? this.getValue(path, setting) : undefined;
}
},
clear: function(path, setting) {
var key = path + '.' + setting;
// Value was not overriden -- nothing to restore
if ( this.originalValues.hasOwnProperty(key) === false ) {
return;
}
var value = this.originalValues[key];
// https://github.com/gorhill/uBlock/issues/292#issuecomment-109621979
// Forget the value immediately, it may change outside of
// uBlock control.
delete this.originalValues[key];
// Original value was a default one
if ( value === undefined ) {
try {
Services.prefs.getBranch(path + '.').clearUserPref(setting);
} catch (ex) {
}
return;
}
// Reset to original value
this.setValue(path, setting, value);
},
getValue: function(path, setting) {
var branch = Services.prefs.getBranch(path + '.');
var getMethod;
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIPrefBranch#getPrefType%28%29
switch ( branch.getPrefType(setting) ) {
case 64: // PREF_INT
getMethod = 'getIntPref';
break;
case 128: // PREF_BOOL
getMethod = 'getBoolPref';
break;
default: // not supported
return;
}
try {
return branch[getMethod](setting);
} catch (ex) {
}
},
setValue: function(path, setting, value) {
var setMethod;
switch ( typeof value ) {
case 'number':
setMethod = 'setIntPref';
break;
case 'boolean':
setMethod = 'setBoolPref';
break;
default: // not supported
return;
}
try {
Services.prefs.getBranch(path + '.')[setMethod](setting, value);
} catch (ex) {
}
},
set: function(details) {
var settingVal;
var prefName, prefVal;
for ( var setting in details ) {
if ( details.hasOwnProperty(setting) === false ) {
continue;
}
settingVal = !!details[setting];
switch ( setting ) {
case 'prefetching':
this.rememberOriginalValue('network', 'prefetch-next');
// http://betanews.com/2015/08/15/firefox-stealthily-loads-webpages-when-you-hover-over-links-heres-how-to-stop-it/
// https://bugzilla.mozilla.org/show_bug.cgi?id=814169
// Sigh.
this.rememberOriginalValue('network.http', 'speculative-parallel-limit');
this.rememberOriginalValue('network.dns', 'disablePrefetch');
// https://github.com/gorhill/uBlock/issues/292
// "true" means "do not disable", i.e. leave entry alone
if ( settingVal ) {
this.clear('network', 'prefetch-next');
this.clear('network.http', 'speculative-parallel-limit');
this.clear('network.dns', 'disablePrefetch');
} else {
this.setValue('network', 'prefetch-next', false);
this.setValue('network.http', 'speculative-parallel-limit', 0);
this.setValue('network.dns', 'disablePrefetch', true);
}
break;
case 'hyperlinkAuditing':
this.rememberOriginalValue('browser', 'send_pings');
// https://github.com/gorhill/uBlock/issues/292
// "true" means "do not disable", i.e. leave entry alone
if ( settingVal ) {
this.clear('browser', 'send_pings');
} else {
this.setValue('browser', 'send_pings', false);
}
break;
// https://github.com/gorhill/uBlock/issues/894
// Do not disable completely WebRTC if it can be avoided. FF42+
// has a `media.peerconnection.ice.default_address_only` pref which
// purpose is to prevent local IP address leakage.
case 'webrtcIPAddress':
if ( this.getValue('media.peerconnection', 'ice.default_address_only') !== undefined ) {
prefName = 'ice.default_address_only';
prefVal = true;
} else {
prefName = 'enabled';
prefVal = false;
}
this.rememberOriginalValue('media.peerconnection', prefName);
if ( settingVal ) {
this.clear('media.peerconnection', prefName);
} else {
this.setValue('media.peerconnection', prefName, prefVal);
}
break;
default:
break;
}
}
},
restoreAll: function() {
var pos;
for ( var key in this.originalValues ) {
if ( this.originalValues.hasOwnProperty(key) === false ) {
continue;
}
pos = key.lastIndexOf('.');
this.clear(key.slice(0, pos), key.slice(pos + 1));
}
}
};
cleanupTasks.push(vAPI.browserSettings.restoreAll.bind(vAPI.browserSettings));
/******************************************************************************/
// API matches that of chrome.storage.local:
// https://developer.chrome.com/extensions/storage
vAPI.storage = (function() {
var db = null;
var vacuumTimer = null;
var dbOpenError = '';
var close = function(now) {
if ( vacuumTimer !== null ) {
clearTimeout(vacuumTimer);
vacuumTimer = null;
}
if ( db === null ) {
return;
}
if ( now ) {
db.close();
} else {
db.asyncClose();
}
db = null;
};
var open = function() {
if ( db !== null ) {
return db;
}
// Create path
var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
path.append('extension-data');
if ( !path.exists() ) {
path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
}
if ( !path.isDirectory() ) {
throw Error('Should be a directory...');
}
path.append(location.host + '.sqlite');
// Open database.
// https://github.com/gorhill/uBlock/issues/1768
// If the SQL file is found to be corrupted at launch time, nuke
// existing SQL file so that a new one can be created.
try {
db = Services.storage.openDatabase(path);
if ( db.connectionReady === false ) {
db.asyncClose();
db = null;
}
} catch (ex) {
if ( dbOpenError === '' ) {
console.error('vAPI.storage/open() error: ', ex.message);
dbOpenError = ex.name;
if ( ex.name === 'NS_ERROR_FILE_CORRUPTED' ) {
nuke();
}
}
}
if ( db === null ) {
return null;
}
// Since database could be opened successfully, reset error flag (its
// purpose is to avoid spamming console with error messages).
dbOpenError = '';
// Database was opened, register cleanup task
cleanupTasks.push(close);
// Setup database
db.createAsyncStatement('CREATE TABLE IF NOT EXISTS "settings" ("name" TEXT PRIMARY KEY NOT NULL, "value" TEXT);')
.executeAsync();
if ( vacuum !== null ) {
vacuumTimer = vAPI.setTimeout(vacuum, 60000);
}
return db;
};
var nuke = function() {
var removeDB = function() {
close(true);
var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
path.append('extension-data');
if ( !path.exists() || !path.isDirectory() ) {
return;
}
path.append(location.host + '.sqlite');
if ( path.exists() ) {
path.remove(false);
}
};
vAPI.setTimeout(removeDB, 1);
};
// https://developer.mozilla.org/en-US/docs/Storage/Performance#Vacuuming_and_zero-fill
// Vacuum only once, and only while idle
var vacuum = function() {
vacuumTimer = null;
if ( db === null ) {
return;
}
var idleSvc = Cc['@mozilla.org/widget/idleservice;1']
.getService(Ci.nsIIdleService);
if ( idleSvc.idleTime < 60000 ) {
vacuumTimer = vAPI.setTimeout(vacuum, 60000);
return;
}
db.createAsyncStatement('VACUUM').executeAsync();
vacuum = null;
};
// Execute a query
var runStatement = function(stmt, callback) {
var result = {};
stmt.executeAsync({
handleResult: function(rows) {
if ( !rows || typeof callback !== 'function' ) {
return;
}
var row;
while ( (row = rows.getNextRow()) ) {
// we assume that there will be two columns, since we're
// using it only for preferences
result[row.getResultByIndex(0)] = row.getResultByIndex(1);
}
},
handleCompletion: function(reason) {
if ( typeof callback === 'function' && reason === 0 ) {
callback(result);
}
result = null;
},
handleError: function(error) {
console.error('SQLite error ', error.result, error.message);
// Caller expects an answer regardless of failure.
if ( typeof callback === 'function' ) {
callback({});
}
result = null;
// https://github.com/gorhill/uBlock/issues/1768
// Error cases which warrant a removal of the SQL file, so far:
// - SQLLite error 11 database disk image is malformed
// Can't find doc on MDN about the type of error.result, so I
// force a string comparison.
if ( error.result.toString() === '11' ) {
nuke();
}
}
});
};
var bindNames = function(stmt, names) {
if ( Array.isArray(names) === false || names.length === 0 ) {
return;
}
var params = stmt.newBindingParamsArray();
var i = names.length, bp;
while ( i-- ) {
bp = params.newBindingParams();
bp.bindByName('name', names[i]);
params.addParams(bp);
}
stmt.bindParameters(params);
};
var clear = function(callback) {
if ( open() === null ) {
if ( typeof callback === 'function' ) {
callback();
}
return;
}
runStatement(db.createAsyncStatement('DELETE FROM "settings";'), callback);
};
var getBytesInUse = function(keys, callback) {
if ( typeof callback !== 'function' ) {
return;
}
if ( open() === null ) {
callback(0);
return;
}
var stmt;
if ( Array.isArray(keys) ) {
stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings" WHERE "name" = :name');
bindNames(keys);
} else {
stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings"');
}
runStatement(stmt, function(result) {
callback(result.size || 0);
});
};
var read = function(details, callback) {
if ( typeof callback !== 'function' ) {
return;
}
var prepareResult = function(result) {
var key;
for ( key in result ) {
if ( result.hasOwnProperty(key) === false ) {
continue;
}
result[key] = JSON.parse(result[key]);
}
if ( typeof details === 'object' && details !== null ) {
for ( key in details ) {
if ( result.hasOwnProperty(key) === false ) {
result[key] = details[key];
}
}
}
callback(result);
};
if ( open() === null ) {
prepareResult({});
return;
}
var names = [];
if ( details !== null ) {
if ( Array.isArray(details) ) {
names = details;
} else if ( typeof details === 'object' ) {
names = Object.keys(details);
} else {
names = [details.toString()];
}
}
var stmt;
if ( names.length === 0 ) {
stmt = db.createAsyncStatement('SELECT * FROM "settings"');
} else {
stmt = db.createAsyncStatement('SELECT * FROM "settings" WHERE "name" = :name');
bindNames(stmt, names);
}
runStatement(stmt, prepareResult);
};
var remove = function(keys, callback) {
if ( open() === null ) {
if ( typeof callback === 'function' ) {
callback();
}
return;
}
var stmt = db.createAsyncStatement('DELETE FROM "settings" WHERE "name" = :name');
bindNames(stmt, typeof keys === 'string' ? [keys] : keys);
runStatement(stmt, callback);
};
var write = function(details, callback) {
if ( open() === null ) {
if ( typeof callback === 'function' ) {
callback();
}
return;
}
var stmt = db.createAsyncStatement('INSERT OR REPLACE INTO "settings" ("name", "value") VALUES(:name, :value)');
var params = stmt.newBindingParamsArray(), bp;
for ( var key in details ) {
if ( details.hasOwnProperty(key) === false ) {
continue;
}
bp = params.newBindingParams();
bp.bindByName('name', key);
bp.bindByName('value', JSON.stringify(details[key]));
params.addParams(bp);
}
if ( params.length === 0 ) {
return;
}
stmt.bindParameters(params);
runStatement(stmt, callback);
};
// Export API
var api = {
QUOTA_BYTES: 100 * 1024 * 1024,
clear: clear,
get: read,
getBytesInUse: getBytesInUse,
remove: remove,
set: write
};
return api;
})();
/******************************************************************************/
// This must be executed/setup early.
var winWatcher = (function() {
var windowToIdMap = new Map();
var windowIdGenerator = 1;
var api = {
onOpenWindow: null,
onCloseWindow: null
};
// https://github.com/gorhill/uMatrix/issues/586
// This is necessary hack because on SeaMonkey 2.40, for unknown reasons
// private windows do not have the attribute `windowtype` set to
// `navigator:browser`. As a fallback, the code here will also test whether
// the id attribute is `main-window`.
api.toBrowserWindow = function(win) {
var docElement = win && win.document && win.document.documentElement;
if ( !docElement ) {
return null;
}
if ( vAPI.thunderbird ) {
return docElement.getAttribute('windowtype') === 'mail:3pane' ? win : null;
}
return docElement.getAttribute('windowtype') === 'navigator:browser' ||
docElement.getAttribute('id') === 'main-window' ?
win : null;
};
api.getWindows = function() {
return windowToIdMap.keys();
};
api.idFromWindow = function(win) {
return windowToIdMap.get(win) || 0;
};
api.getCurrentWindow = function() {
return this.toBrowserWindow(Services.wm.getMostRecentWindow(null));
};
var addWindow = function(win) {
if ( !win || windowToIdMap.has(win) ) {
return;
}
windowToIdMap.set(win, windowIdGenerator++);
if ( typeof api.onOpenWindow === 'function' ) {
api.onOpenWindow(win);
}
};
var removeWindow = function(win) {
if ( !win || windowToIdMap.delete(win) !== true ) {
return;
}
if ( typeof api.onCloseWindow === 'function' ) {
api.onCloseWindow(win);
}
};
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowMediator
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher
// https://github.com/gorhill/uMatrix/issues/357
// Use nsIWindowMediator for being notified of opened/closed windows.
var listeners = {
onOpenWindow: function(aWindow) {
var win;
try {
win = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
} catch (ex) {
}
addWindow(win);
},
onCloseWindow: function(aWindow) {
var win;
try {
win = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
} catch (ex) {
}
removeWindow(win);
},
observe: function(aSubject, topic) {
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher#registerNotification%28%29
// "aSubject - the window being opened or closed, sent as an
// "nsISupports which can be ... QueryInterfaced to an
// "nsIDOMWindow."
var win;
try {
win = aSubject.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
} catch (ex) {
}
if ( !win ) { return; }
if ( topic === 'domwindowopened' ) {
addWindow(win);
return;
}
if ( topic === 'domwindowclosed' ) {
removeWindow(win);
return;
}
}
};
(function() {
var winumerator, win;
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowMediator#getEnumerator%28%29
winumerator = Services.wm.getEnumerator(null);
while ( winumerator.hasMoreElements() ) {
win = winumerator.getNext();
if ( !win.closed ) {
windowToIdMap.set(win, windowIdGenerator++);
}
}
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher#getWindowEnumerator%28%29
winumerator = Services.ww.getWindowEnumerator();
while ( winumerator.hasMoreElements() ) {
win = winumerator.getNext()
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
if ( !win.closed ) {
windowToIdMap.set(win, windowIdGenerator++);
}
}
Services.wm.addListener(listeners);
Services.ww.registerNotification(listeners);
})();
cleanupTasks.push(function() {
Services.wm.removeListener(listeners);
Services.ww.unregisterNotification(listeners);
windowToIdMap.clear();
});
return api;
})();
/******************************************************************************/
var getTabBrowser = (function() {
if ( vAPI.fennec ) {
return function(win) {
return win.BrowserApp || null;
};
}
if ( vAPI.thunderbird ) {
return function(win) {
return win.document.getElementById('tabmail') || null;
};
}
// https://github.com/gorhill/uBlock/issues/1004
// Merely READING the `gBrowser` property causes the issue -- no
// need to even use its returned value... This really should be fixed
// in the browser.
// Meanwhile, the workaround is to check whether the document is
// ready. This is hacky, as the code below has to make assumption
// about the browser's inner working -- specifically that the `gBrowser`
// property should NOT be accessed before the document of the window is
// in its ready state.
return function(win) {
if ( win ) {
var doc = win.document;
if ( doc && doc.readyState === 'complete' ) {
return win.gBrowser || null;
}
}
return null;
};
})();
/******************************************************************************/
var getOwnerWindow = function(target) {
if ( target.ownerDocument ) {
return target.ownerDocument.defaultView;
}
// Fennec
for ( var win of winWatcher.getWindows() ) {
for ( var tab of win.BrowserApp.tabs) {
if ( tab === target || tab.window === target ) {
return win;
}
}
}
return null;
};
/******************************************************************************/
vAPI.isBehindTheSceneTabId = function(tabId) {
return tabId.toString() === '-1';
};
vAPI.noTabId = '-1';
/******************************************************************************/
vAPI.tabs = {};
/******************************************************************************/
vAPI.tabs.registerListeners = function() {
tabWatcher.start();
};
/******************************************************************************/
// Firefox:
// https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser
//
// browser --> ownerDocument --> defaultView --> gBrowser --> browsers --+
// ^ |
// | |
// +-------------------------------------------------------------------
//
// browser (browser)
// contentTitle
// currentURI
// ownerDocument (XULDocument)
// defaultView (ChromeWindow)
// gBrowser (tabbrowser OR browser)
// browsers (browser)
// selectedBrowser
// selectedTab
// tabs (tab.tabbrowser-tab)
//
// Fennec: (what I figured so far)
//
// tab --> browser windows --> window --> BrowserApp --> tabs --+
// ^ window |
// | |
// +---------------------------------------------------------------+
//
// tab
// browser
// [manual search to go back to tab from list of windows]
vAPI.tabs.get = function(tabId, callback) {
var browser;
if ( tabId === null ) {
browser = tabWatcher.currentBrowser();
tabId = tabWatcher.tabIdFromTarget(browser);
} else {
browser = tabWatcher.browserFromTabId(tabId);
}
// For internal use
if ( typeof callback !== 'function' ) {
return browser;
}
if ( !browser || !browser.currentURI ) {
callback();
return;
}
var win = getOwnerWindow(browser);
var tabBrowser = getTabBrowser(win);
// https://github.com/gorhill/uMatrix/issues/540
// The `index` property is nowhere used by uBlock at this point, so we
// will refrain from returning this information for the time being.
callback({
id: tabId,
index: undefined,
windowId: winWatcher.idFromWindow(win),
active: tabBrowser !== null && browser === tabBrowser.selectedBrowser,
url: browser.currentURI.asciiSpec,
title: browser.contentTitle
});
};
/******************************************************************************/
vAPI.tabs.getAll = function(window) {
var win, tab;
var tabs = [];
for ( win of winWatcher.getWindows() ) {
if ( window && window !== win ) {
continue;
}
var tabBrowser = getTabBrowser(win);
if ( tabBrowser === null ) {
continue;
}
// This can happens if a tab-less window is currently opened.
// Example of a tab-less window: one opened from clicking
// "View Page Source".
if ( !tabBrowser.tabs ) {
continue;
}
for ( tab of tabBrowser.tabs ) {
tabs.push(tab);
}
}
return tabs;
};
/******************************************************************************/
// 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
vAPI.tabs.open = function(details) {
if ( !details.url ) {
return null;
}
// extension pages
if ( /^[\w-]{2,}:/.test(details.url) === false ) {
details.url = vAPI.getURL(details.url);
}
var tab;
if ( details.select ) {
var URI = Services.io.newURI(details.url, null, null);
for ( tab of this.getAll() ) {
var browser = tabWatcher.browserFromTarget(tab);
// Or simply .equals if we care about the fragment
if ( URI.equalsExceptRef(browser.currentURI) === false ) {
continue;
}
this.select(tab);
// Update URL if fragment is different
if ( URI.equals(browser.currentURI) === false ) {
browser.loadURI(URI.asciiSpec);
}
return;
}
}
if ( details.active === undefined ) {
details.active = true;
}
if ( details.tabId ) {
tab = tabWatcher.browserFromTabId(details.tabId);
if ( tab ) {
tabWatcher.browserFromTarget(tab).loadURI(details.url);
return;
}
}
var win = winWatcher.getCurrentWindow();
var tabBrowser = getTabBrowser(win);
if ( tabBrowser === null ) {
return;
}
if ( vAPI.fennec ) {
tabBrowser.addTab(details.url, {
selected: details.active !== false,