You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3465 lines
108 KiB

9 years ago
8 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
9 years ago
10 years ago
10 years ago
10 years ago
8 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
  1. /*******************************************************************************
  2. uMatrix - a browser extension to block requests.
  3. Copyright (C) 2014-2017 The uMatrix/uBlock Origin authors
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see {http://www.gnu.org/licenses/}.
  14. Home: https://github.com/gorhill/uMatrix
  15. */
  16. /* jshint bitwise: false, esnext: true */
  17. /* global self, Components, punycode */
  18. // For background page
  19. 'use strict';
  20. /******************************************************************************/
  21. (function() {
  22. /******************************************************************************/
  23. // Useful links
  24. //
  25. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface
  26. // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Services.jsm
  27. /******************************************************************************/
  28. const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
  29. const {Services} = Cu.import('resource://gre/modules/Services.jsm', null);
  30. /******************************************************************************/
  31. var vAPI = self.vAPI = self.vAPI || {};
  32. vAPI.firefox = true;
  33. vAPI.modernFirefox = Services.appinfo.ID === '{ec8030f7-c20a-464f-9b0e-13a3a9e97384}' &&
  34. Services.vc.compare(Services.appinfo.platformVersion, '44') > 0;
  35. /******************************************************************************/
  36. var deferUntil = function(testFn, mainFn, details) {
  37. if ( typeof details !== 'object' ) {
  38. details = {};
  39. }
  40. var now = 0;
  41. var next = details.next || 200;
  42. var until = details.until || 2000;
  43. var check = function() {
  44. if ( testFn() === true || now >= until ) {
  45. mainFn();
  46. return;
  47. }
  48. now += next;
  49. vAPI.setTimeout(check, next);
  50. };
  51. if ( 'sync' in details && details.sync === true ) {
  52. check();
  53. } else {
  54. vAPI.setTimeout(check, 1);
  55. }
  56. };
  57. /******************************************************************************/
  58. vAPI.app = {
  59. name: 'uMatrix',
  60. version: location.hash.slice(1)
  61. };
  62. /******************************************************************************/
  63. vAPI.app.start = function() {
  64. };
  65. /******************************************************************************/
  66. vAPI.app.stop = function() {
  67. };
  68. /******************************************************************************/
  69. vAPI.app.restart = function() {
  70. // Listening in bootstrap.js
  71. Cc['@mozilla.org/childprocessmessagemanager;1']
  72. .getService(Ci.nsIMessageSender)
  73. .sendAsyncMessage(location.host + '-restart');
  74. };
  75. /******************************************************************************/
  76. // List of things that needs to be destroyed when disabling the extension
  77. // Only functions should be added to it
  78. var cleanupTasks = [];
  79. // This must be updated manually, every time a new task is added/removed
  80. // Fixed by github.com/AlexVallat:
  81. // https://github.com/AlexVallat/uBlock/commit/7b781248f00cbe3d61b1cc367c440db80fa06049
  82. // 7 instances of cleanupTasks.push, but one is unique to fennec, and one to desktop.
  83. var expectedNumberOfCleanups = 7;
  84. window.addEventListener('unload', function() {
  85. if ( typeof vAPI.app.onShutdown === 'function' ) {
  86. vAPI.app.onShutdown();
  87. }
  88. // IMPORTANT: cleanup tasks must be executed using LIFO order.
  89. var i = cleanupTasks.length;
  90. while ( i-- ) {
  91. cleanupTasks[i]();
  92. }
  93. if ( cleanupTasks.length < expectedNumberOfCleanups ) {
  94. console.error(
  95. 'uMatrix> Cleanup tasks performed: %s (out of %s)',
  96. cleanupTasks.length,
  97. expectedNumberOfCleanups
  98. );
  99. }
  100. // frameModule needs to be cleared too
  101. var frameModuleURL = vAPI.getURL('frameModule.js');
  102. var frameModule = {};
  103. Cu.import(frameModuleURL, frameModule);
  104. frameModule.contentObserver.unregister();
  105. Cu.unload(frameModuleURL);
  106. });
  107. /******************************************************************************/
  108. // For now, only booleans.
  109. vAPI.browserSettings = {
  110. originalValues: {},
  111. rememberOriginalValue: function(path, setting) {
  112. var key = path + '.' + setting;
  113. if ( this.originalValues.hasOwnProperty(key) ) {
  114. return;
  115. }
  116. var hasUserValue;
  117. var branch = Services.prefs.getBranch(path + '.');
  118. try {
  119. hasUserValue = branch.prefHasUserValue(setting);
  120. } catch (ex) {
  121. }
  122. if ( hasUserValue !== undefined ) {
  123. this.originalValues[key] = hasUserValue ? this.getValue(path, setting) : undefined;
  124. }
  125. },
  126. clear: function(path, setting) {
  127. var key = path + '.' + setting;
  128. // Value was not overriden -- nothing to restore
  129. if ( this.originalValues.hasOwnProperty(key) === false ) {
  130. return;
  131. }
  132. var value = this.originalValues[key];
  133. // https://github.com/gorhill/uBlock/issues/292#issuecomment-109621979
  134. // Forget the value immediately, it may change outside of
  135. // uBlock control.
  136. delete this.originalValues[key];
  137. // Original value was a default one
  138. if ( value === undefined ) {
  139. try {
  140. Services.prefs.getBranch(path + '.').clearUserPref(setting);
  141. } catch (ex) {
  142. }
  143. return;
  144. }
  145. // Reset to original value
  146. this.setValue(path, setting, value);
  147. },
  148. getValue: function(path, setting) {
  149. var branch = Services.prefs.getBranch(path + '.');
  150. var getMethod;
  151. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIPrefBranch#getPrefType%28%29
  152. switch ( branch.getPrefType(setting) ) {
  153. case 64: // PREF_INT
  154. getMethod = 'getIntPref';
  155. break;
  156. case 128: // PREF_BOOL
  157. getMethod = 'getBoolPref';
  158. break;
  159. default: // not supported
  160. return;
  161. }
  162. try {
  163. return branch[getMethod](setting);
  164. } catch (ex) {
  165. }
  166. },
  167. setValue: function(path, setting, value) {
  168. var setMethod;
  169. switch ( typeof value ) {
  170. case 'number':
  171. setMethod = 'setIntPref';
  172. break;
  173. case 'boolean':
  174. setMethod = 'setBoolPref';
  175. break;
  176. default: // not supported
  177. return;
  178. }
  179. try {
  180. Services.prefs.getBranch(path + '.')[setMethod](setting, value);
  181. } catch (ex) {
  182. }
  183. },
  184. setSetting: function(setting, value) {
  185. var prefName, prefVal;
  186. switch ( setting ) {
  187. case 'prefetching':
  188. this.rememberOriginalValue('network', 'prefetch-next');
  189. // http://betanews.com/2015/08/15/firefox-stealthily-loads-webpages-when-you-hover-over-links-heres-how-to-stop-it/
  190. // https://bugzilla.mozilla.org/show_bug.cgi?id=814169
  191. // Sigh.
  192. this.rememberOriginalValue('network.http', 'speculative-parallel-limit');
  193. // https://github.com/gorhill/uBlock/issues/292
  194. // "true" means "do not disable", i.e. leave entry alone
  195. if ( value ) {
  196. this.clear('network', 'prefetch-next');
  197. this.clear('network.http', 'speculative-parallel-limit');
  198. } else {
  199. this.setValue('network', 'prefetch-next', false);
  200. this.setValue('network.http', 'speculative-parallel-limit', 0);
  201. }
  202. break;
  203. case 'hyperlinkAuditing':
  204. this.rememberOriginalValue('browser', 'send_pings');
  205. this.rememberOriginalValue('beacon', 'enabled');
  206. // https://github.com/gorhill/uBlock/issues/292
  207. // "true" means "do not disable", i.e. leave entry alone
  208. if ( value ) {
  209. this.clear('browser', 'send_pings');
  210. this.clear('beacon', 'enabled');
  211. } else {
  212. this.setValue('browser', 'send_pings', false);
  213. this.setValue('beacon', 'enabled', false);
  214. }
  215. break;
  216. // https://github.com/gorhill/uBlock/issues/894
  217. // Do not disable completely WebRTC if it can be avoided. FF42+
  218. // has a `media.peerconnection.ice.default_address_only` pref which
  219. // purpose is to prevent local IP address leakage.
  220. case 'webrtcIPAddress':
  221. if ( this.getValue('media.peerconnection', 'ice.default_address_only') !== undefined ) {
  222. prefName = 'ice.default_address_only';
  223. prefVal = true;
  224. } else {
  225. prefName = 'enabled';
  226. prefVal = false;
  227. }
  228. this.rememberOriginalValue('media.peerconnection', prefName);
  229. if ( value ) {
  230. this.clear('media.peerconnection', prefName);
  231. } else {
  232. this.setValue('media.peerconnection', prefName, prefVal);
  233. }
  234. break;
  235. default:
  236. break;
  237. }
  238. },
  239. set: function(details) {
  240. for ( var setting in details ) {
  241. if ( details.hasOwnProperty(setting) === false ) {
  242. continue;
  243. }
  244. this.setSetting(setting, !!details[setting]);
  245. }
  246. },
  247. restoreAll: function() {
  248. var pos;
  249. for ( var key in this.originalValues ) {
  250. if ( this.originalValues.hasOwnProperty(key) === false ) {
  251. continue;
  252. }
  253. pos = key.lastIndexOf('.');
  254. this.clear(key.slice(0, pos), key.slice(pos + 1));
  255. }
  256. }
  257. };
  258. cleanupTasks.push(vAPI.browserSettings.restoreAll.bind(vAPI.browserSettings));
  259. /******************************************************************************/
  260. // API matches that of chrome.storage.local:
  261. // https://developer.chrome.com/extensions/storage
  262. vAPI.storage = (function() {
  263. var db = null;
  264. var vacuumTimer = null;
  265. var close = function() {
  266. if ( vacuumTimer !== null ) {
  267. clearTimeout(vacuumTimer);
  268. vacuumTimer = null;
  269. }
  270. if ( db === null ) {
  271. return;
  272. }
  273. db.asyncClose();
  274. db = null;
  275. };
  276. var open = function() {
  277. if ( db !== null ) {
  278. return db;
  279. }
  280. // Create path
  281. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  282. path.append('extension-data');
  283. if ( !path.exists() ) {
  284. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  285. }
  286. if ( !path.isDirectory() ) {
  287. throw Error('Should be a directory...');
  288. }
  289. path.append(location.host + '.sqlite');
  290. // Open database
  291. try {
  292. db = Services.storage.openDatabase(path);
  293. if ( db.connectionReady === false ) {
  294. db.asyncClose();
  295. db = null;
  296. }
  297. } catch (ex) {
  298. }
  299. if ( db === null ) {
  300. return null;
  301. }
  302. // Database was opened, register cleanup task
  303. cleanupTasks.push(close);
  304. // Setup database
  305. db.createAsyncStatement('CREATE TABLE IF NOT EXISTS "settings" ("name" TEXT PRIMARY KEY NOT NULL, "value" TEXT);')
  306. .executeAsync();
  307. if ( vacuum !== null ) {
  308. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  309. }
  310. return db;
  311. };
  312. // https://developer.mozilla.org/en-US/docs/Storage/Performance#Vacuuming_and_zero-fill
  313. // Vacuum only once, and only while idle
  314. var vacuum = function() {
  315. vacuumTimer = null;
  316. if ( db === null ) {
  317. return;
  318. }
  319. var idleSvc = Cc['@mozilla.org/widget/idleservice;1']
  320. .getService(Ci.nsIIdleService);
  321. if ( idleSvc.idleTime < 60000 ) {
  322. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  323. return;
  324. }
  325. db.createAsyncStatement('VACUUM').executeAsync();
  326. vacuum = null;
  327. };
  328. // Execute a query
  329. var runStatement = function(stmt, callback) {
  330. var result = {};
  331. stmt.executeAsync({
  332. handleResult: function(rows) {
  333. if ( !rows || typeof callback !== 'function' ) {
  334. return;
  335. }
  336. var row;
  337. while ( (row = rows.getNextRow()) ) {
  338. // we assume that there will be two columns, since we're
  339. // using it only for preferences
  340. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  341. }
  342. },
  343. handleCompletion: function(reason) {
  344. if ( typeof callback === 'function' && reason === 0 ) {
  345. callback(result);
  346. }
  347. },
  348. handleError: function(error) {
  349. console.error('SQLite error ', error.result, error.message);
  350. // Caller expects an answer regardless of failure.
  351. if ( typeof callback === 'function' ) {
  352. callback(null);
  353. }
  354. }
  355. });
  356. };
  357. var bindNames = function(stmt, names) {
  358. if ( Array.isArray(names) === false || names.length === 0 ) {
  359. return;
  360. }
  361. var params = stmt.newBindingParamsArray();
  362. var i = names.length, bp;
  363. while ( i-- ) {
  364. bp = params.newBindingParams();
  365. bp.bindByName('name', names[i]);
  366. params.addParams(bp);
  367. }
  368. stmt.bindParameters(params);
  369. };
  370. var clear = function(callback) {
  371. if ( open() === null ) {
  372. if ( typeof callback === 'function' ) {
  373. callback();
  374. }
  375. return;
  376. }
  377. runStatement(db.createAsyncStatement('DELETE FROM "settings";'), callback);
  378. };
  379. var getBytesInUse = function(keys, callback) {
  380. if ( typeof callback !== 'function' ) {
  381. return;
  382. }
  383. if ( open() === null ) {
  384. callback(0);
  385. return;
  386. }
  387. var stmt;
  388. if ( Array.isArray(keys) ) {
  389. stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings" WHERE "name" = :name');
  390. bindNames(keys);
  391. } else {
  392. stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings"');
  393. }
  394. runStatement(stmt, function(result) {
  395. callback(result.size);
  396. });
  397. };
  398. var read = function(details, callback) {
  399. if ( typeof callback !== 'function' ) {
  400. return;
  401. }
  402. var prepareResult = function(result) {
  403. var key;
  404. for ( key in result ) {
  405. if ( result.hasOwnProperty(key) === false ) {
  406. continue;
  407. }
  408. result[key] = JSON.parse(result[key]);
  409. }
  410. if ( typeof details === 'object' && details !== null ) {
  411. for ( key in details ) {
  412. if ( result.hasOwnProperty(key) === false ) {
  413. result[key] = details[key];
  414. }
  415. }
  416. }
  417. callback(result);
  418. };
  419. if ( open() === null ) {
  420. prepareResult({});
  421. return;
  422. }
  423. var names = [];
  424. if ( details !== null ) {
  425. if ( Array.isArray(details) ) {
  426. names = details;
  427. } else if ( typeof details === 'object' ) {
  428. names = Object.keys(details);
  429. } else {
  430. names = [details.toString()];
  431. }
  432. }
  433. var stmt;
  434. if ( names.length === 0 ) {
  435. stmt = db.createAsyncStatement('SELECT * FROM "settings"');
  436. } else {
  437. stmt = db.createAsyncStatement('SELECT * FROM "settings" WHERE "name" = :name');
  438. bindNames(stmt, names);
  439. }
  440. runStatement(stmt, prepareResult);
  441. };
  442. var remove = function(keys, callback) {
  443. if ( open() === null ) {
  444. if ( typeof callback === 'function' ) {
  445. callback();
  446. }
  447. return;
  448. }
  449. var stmt = db.createAsyncStatement('DELETE FROM "settings" WHERE "name" = :name');
  450. bindNames(stmt, typeof keys === 'string' ? [keys] : keys);
  451. runStatement(stmt, callback);
  452. };
  453. var write = function(details, callback) {
  454. if ( open() === null ) {
  455. if ( typeof callback === 'function' ) {
  456. callback();
  457. }
  458. return;
  459. }
  460. var stmt = db.createAsyncStatement('INSERT OR REPLACE INTO "settings" ("name", "value") VALUES(:name, :value)');
  461. var params = stmt.newBindingParamsArray(), bp;
  462. for ( var key in details ) {
  463. if ( details.hasOwnProperty(key) === false ) {
  464. continue;
  465. }
  466. bp = params.newBindingParams();
  467. bp.bindByName('name', key);
  468. bp.bindByName('value', JSON.stringify(details[key]));
  469. params.addParams(bp);
  470. }
  471. if ( params.length === 0 ) {
  472. return;
  473. }
  474. stmt.bindParameters(params);
  475. runStatement(stmt, callback);
  476. };
  477. // Export API
  478. var api = {
  479. QUOTA_BYTES: 100 * 1024 * 1024,
  480. clear: clear,
  481. get: read,
  482. getBytesInUse: getBytesInUse,
  483. remove: remove,
  484. set: write
  485. };
  486. return api;
  487. })();
  488. vAPI.cacheStorage = vAPI.storage;
  489. /******************************************************************************/
  490. // This must be executed/setup early.
  491. var winWatcher = (function() {
  492. var windowToIdMap = new Map();
  493. var windowIdGenerator = 1;
  494. var api = {
  495. onOpenWindow: null,
  496. onCloseWindow: null
  497. };
  498. // https://github.com/gorhill/uMatrix/issues/586
  499. // This is necessary hack because on SeaMonkey 2.40, for unknown reasons
  500. // private windows do not have the attribute `windowtype` set to
  501. // `navigator:browser`. As a fallback, the code here will also test whether
  502. // the id attribute is `main-window`.
  503. api.toBrowserWindow = function(win) {
  504. var docElement = win && win.document && win.document.documentElement;
  505. if ( !docElement ) {
  506. return null;
  507. }
  508. if ( vAPI.thunderbird ) {
  509. return docElement.getAttribute('windowtype') === 'mail:3pane' ? win : null;
  510. }
  511. return docElement.getAttribute('windowtype') === 'navigator:browser' ||
  512. docElement.getAttribute('id') === 'main-window' ?
  513. win : null;
  514. };
  515. api.getWindows = function() {
  516. return windowToIdMap.keys();
  517. };
  518. api.idFromWindow = function(win) {
  519. return windowToIdMap.get(win) || 0;
  520. };
  521. api.getCurrentWindow = function() {
  522. return this.toBrowserWindow(Services.wm.getMostRecentWindow(null));
  523. };
  524. var addWindow = function(win) {
  525. if ( !win || windowToIdMap.has(win) ) {
  526. return;
  527. }
  528. windowToIdMap.set(win, windowIdGenerator++);
  529. if ( typeof api.onOpenWindow === 'function' ) {
  530. api.onOpenWindow(win);
  531. }
  532. };
  533. var removeWindow = function(win) {
  534. if ( !win || windowToIdMap.delete(win) !== true ) {
  535. return;
  536. }
  537. if ( typeof api.onCloseWindow === 'function' ) {
  538. api.onCloseWindow(win);
  539. }
  540. };
  541. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowMediator
  542. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher
  543. // https://github.com/gorhill/uMatrix/issues/357
  544. // Use nsIWindowMediator for being notified of opened/closed windows.
  545. var listeners = {
  546. onOpenWindow: function(aWindow) {
  547. var win;
  548. try {
  549. win = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
  550. .getInterface(Ci.nsIDOMWindow);
  551. } catch (ex) {
  552. }
  553. addWindow(win);
  554. },
  555. onCloseWindow: function(aWindow) {
  556. var win;
  557. try {
  558. win = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
  559. .getInterface(Ci.nsIDOMWindow);
  560. } catch (ex) {
  561. }
  562. removeWindow(win);
  563. },
  564. observe: function(aSubject, topic) {
  565. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher#registerNotification%28%29
  566. // "aSubject - the window being opened or closed, sent as an
  567. // "nsISupports which can be ... QueryInterfaced to an
  568. // "nsIDOMWindow."
  569. var win;
  570. try {
  571. win = aSubject.QueryInterface(Ci.nsIInterfaceRequestor)
  572. .getInterface(Ci.nsIDOMWindow);
  573. } catch (ex) {
  574. }
  575. if ( !win ) { return; }
  576. if ( topic === 'domwindowopened' ) {
  577. addWindow(win);
  578. return;
  579. }
  580. if ( topic === 'domwindowclosed' ) {
  581. removeWindow(win);
  582. return;
  583. }
  584. }
  585. };
  586. (function() {
  587. var winumerator, win;
  588. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowMediator#getEnumerator%28%29
  589. winumerator = Services.wm.getEnumerator(null);
  590. while ( winumerator.hasMoreElements() ) {
  591. win = winumerator.getNext();
  592. if ( !win.closed ) {
  593. windowToIdMap.set(win, windowIdGenerator++);
  594. }
  595. }
  596. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher#getWindowEnumerator%28%29
  597. winumerator = Services.ww.getWindowEnumerator();
  598. while ( winumerator.hasMoreElements() ) {
  599. win = winumerator.getNext()
  600. .QueryInterface(Ci.nsIInterfaceRequestor)
  601. .getInterface(Ci.nsIDOMWindow);
  602. if ( !win.closed ) {
  603. windowToIdMap.set(win, windowIdGenerator++);
  604. }
  605. }
  606. Services.wm.addListener(listeners);
  607. Services.ww.registerNotification(listeners);
  608. })();
  609. cleanupTasks.push(function() {
  610. Services.wm.removeListener(listeners);
  611. Services.ww.unregisterNotification(listeners);
  612. windowToIdMap.clear();
  613. });
  614. return api;
  615. })();
  616. /******************************************************************************/
  617. var getTabBrowser = function(win) {
  618. return win && win.gBrowser || null;
  619. };
  620. /******************************************************************************/
  621. var getOwnerWindow = function(target) {
  622. if ( target.ownerDocument ) {
  623. return target.ownerDocument.defaultView;
  624. }
  625. return null;
  626. };
  627. /******************************************************************************/
  628. vAPI.isBehindTheSceneTabId = function(tabId) {
  629. return tabId.toString() === '-1';
  630. };
  631. vAPI.noTabId = '-1';
  632. /******************************************************************************/
  633. vAPI.tabs = {};
  634. /******************************************************************************/
  635. vAPI.tabs.registerListeners = function() {
  636. tabWatcher.start();
  637. };
  638. /******************************************************************************/
  639. // Firefox:
  640. // https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser
  641. //
  642. // browser --> ownerDocument --> defaultView --> gBrowser --> browsers --+
  643. // ^ |
  644. // | |
  645. // +-------------------------------------------------------------------
  646. //
  647. // browser (browser)
  648. // contentTitle
  649. // currentURI
  650. // ownerDocument (XULDocument)
  651. // defaultView (ChromeWindow)
  652. // gBrowser (tabbrowser OR browser)
  653. // browsers (browser)
  654. // selectedBrowser
  655. // selectedTab
  656. // tabs (tab.tabbrowser-tab)
  657. //
  658. // Fennec: (what I figured so far)
  659. //
  660. // tab --> browser windows --> window --> BrowserApp --> tabs --+
  661. // ^ window |
  662. // | |
  663. // +---------------------------------------------------------------+
  664. //
  665. // tab
  666. // browser
  667. // [manual search to go back to tab from list of windows]
  668. vAPI.tabs.get = function(tabId, callback) {
  669. var browser;
  670. if ( tabId === null ) {
  671. browser = tabWatcher.currentBrowser();
  672. tabId = tabWatcher.tabIdFromTarget(browser);
  673. } else {
  674. browser = tabWatcher.browserFromTabId(tabId);
  675. }
  676. // For internal use
  677. if ( typeof callback !== 'function' ) {
  678. return browser;
  679. }
  680. if ( !browser || !browser.currentURI ) {
  681. callback();
  682. return;
  683. }
  684. var win = getOwnerWindow(browser);
  685. var tabBrowser = getTabBrowser(win);
  686. // https://github.com/gorhill/uMatrix/issues/540
  687. // The `index` property is nowhere used by uMatrix at this point, so we
  688. // will refrain from returning this information for the time being.
  689. callback({
  690. id: tabId,
  691. index: undefined,
  692. windowId: winWatcher.idFromWindow(win),
  693. active: tabBrowser !== null && browser === tabBrowser.selectedBrowser,
  694. url: browser.currentURI.asciiSpec,
  695. title: browser.contentTitle
  696. });
  697. };
  698. /******************************************************************************/
  699. vAPI.tabs.getAllSync = function(window) {
  700. var win, tab;
  701. var tabs = [];
  702. for ( win of winWatcher.getWindows() ) {
  703. if ( window && window !== win ) {
  704. continue;
  705. }
  706. var tabBrowser = getTabBrowser(win);
  707. if ( tabBrowser === null ) {
  708. continue;
  709. }
  710. // This can happens if a tab-less window is currently opened.
  711. // Example of a tab-less window: one opened from clicking
  712. // "View Page Source".
  713. if ( !tabBrowser.tabs ) {
  714. continue;
  715. }
  716. for ( tab of tabBrowser.tabs ) {
  717. tabs.push(tab);
  718. }
  719. }
  720. return tabs;
  721. };
  722. /******************************************************************************/
  723. vAPI.tabs.getAll = function(callback) {
  724. var tabs = [], tab;
  725. for ( var browser of tabWatcher.browsers() ) {
  726. tab = tabWatcher.tabFromBrowser(browser);
  727. if ( tab === null ) {
  728. continue;
  729. }
  730. if ( tab.hasAttribute('pending') ) {
  731. continue;
  732. }
  733. tabs.push({
  734. id: tabWatcher.tabIdFromTarget(browser),
  735. url: browser.currentURI.asciiSpec
  736. });
  737. }
  738. callback(tabs);
  739. };
  740. /******************************************************************************/
  741. // properties of the details object:
  742. // url: 'URL', // the address that will be opened
  743. // tabId: 1, // the tab is used if set, instead of creating a new one
  744. // index: -1, // undefined: end of the list, -1: following tab, or after index
  745. // active: false, // opens the tab in background - true and undefined: foreground
  746. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  747. vAPI.tabs.open = function(details) {
  748. if ( !details.url ) {
  749. return null;
  750. }
  751. // extension pages
  752. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  753. details.url = vAPI.getURL(details.url);
  754. }
  755. var tab;
  756. if ( details.select ) {
  757. var URI = Services.io.newURI(details.url, null, null);
  758. for ( tab of this.getAllSync() ) {
  759. var browser = tabWatcher.browserFromTarget(tab);
  760. // https://github.com/gorhill/uBlock/issues/2558
  761. if ( browser === null ) { continue; }
  762. // Or simply .equals if we care about the fragment
  763. if ( URI.equalsExceptRef(browser.currentURI) === false ) {
  764. continue;
  765. }
  766. this.select(tab);
  767. // Update URL if fragment is different
  768. if ( URI.equals(browser.currentURI) === false ) {
  769. browser.loadURI(URI.asciiSpec);
  770. }
  771. return;
  772. }
  773. }
  774. if ( details.active === undefined ) {
  775. details.active = true;
  776. }
  777. if ( details.tabId ) {
  778. tab = tabWatcher.browserFromTabId(details.tabId);
  779. if ( tab ) {
  780. tabWatcher.browserFromTarget(tab).loadURI(details.url);
  781. return;
  782. }
  783. }
  784. // Open in a standalone window
  785. if ( details.popup === true ) {
  786. Services.ww.openWindow(
  787. self,
  788. details.url,
  789. null,
  790. 'location=1,menubar=1,personalbar=1,resizable=1,toolbar=1',
  791. null
  792. );
  793. return;
  794. }
  795. var win = winWatcher.getCurrentWindow();
  796. var tabBrowser = getTabBrowser(win);
  797. if ( tabBrowser === null ) {
  798. return;
  799. }
  800. if ( details.index === -1 ) {
  801. details.index = tabBrowser.browsers.indexOf(tabBrowser.selectedBrowser) + 1;
  802. }
  803. tab = tabBrowser.loadOneTab(details.url, { inBackground: !details.active });
  804. if ( details.index !== undefined ) {
  805. tabBrowser.moveTabTo(tab, details.index);
  806. }
  807. };
  808. /******************************************************************************/
  809. // Replace the URL of a tab. Noop if the tab does not exist.
  810. vAPI.tabs.replace = function(tabId, url) {
  811. var targetURL = url;
  812. // extension pages
  813. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  814. targetURL = vAPI.getURL(targetURL);
  815. }
  816. var browser = tabWatcher.browserFromTabId(tabId);
  817. if ( browser ) {
  818. browser.loadURI(targetURL);
  819. }
  820. };
  821. /******************************************************************************/
  822. vAPI.tabs._remove = function(tab, tabBrowser) {
  823. if ( tabBrowser ) {
  824. tabBrowser.removeTab(tab);
  825. }
  826. };
  827. /******************************************************************************/
  828. vAPI.tabs.remove = function(tabId) {
  829. var browser = tabWatcher.browserFromTabId(tabId);
  830. if ( !browser ) {
  831. return;
  832. }
  833. var tab = tabWatcher.tabFromBrowser(browser);
  834. if ( !tab ) {
  835. return;
  836. }
  837. this._remove(tab, getTabBrowser(getOwnerWindow(browser)));
  838. };
  839. /******************************************************************************/
  840. vAPI.tabs.reload = function(tabId) {
  841. var browser = tabWatcher.browserFromTabId(tabId);
  842. if ( !browser ) {
  843. return;
  844. }
  845. browser.webNavigation.reload(Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE);
  846. };
  847. /******************************************************************************/
  848. vAPI.tabs.select = function(tab) {
  849. if ( typeof tab !== 'object' ) {
  850. tab = tabWatcher.tabFromBrowser(tabWatcher.browserFromTabId(tab));
  851. }
  852. if ( !tab ) {
  853. return;
  854. }
  855. // https://github.com/gorhill/uBlock/issues/470
  856. var win = getOwnerWindow(tab);
  857. win.focus();
  858. var tabBrowser = getTabBrowser(win);
  859. if ( tabBrowser ) {
  860. tabBrowser.selectedTab = tab;
  861. }
  862. };
  863. /******************************************************************************/
  864. vAPI.tabs.injectScript = function(tabId, details, callback) {
  865. var browser = tabWatcher.browserFromTabId(tabId);
  866. if ( !browser ) {
  867. return;
  868. }
  869. if ( typeof details.file !== 'string' ) {
  870. return;
  871. }
  872. details.file = vAPI.getURL(details.file);
  873. browser.messageManager.sendAsyncMessage(
  874. location.host + ':broadcast',
  875. JSON.stringify({
  876. broadcast: true,
  877. channelName: 'vAPI',
  878. msg: {
  879. cmd: 'injectScript',
  880. details: details
  881. }
  882. })
  883. );
  884. if ( typeof callback === 'function' ) {
  885. vAPI.setTimeout(callback, 13);
  886. }
  887. };
  888. /******************************************************************************/
  889. var tabWatcher = (function() {
  890. // TODO: find out whether we need a janitor to take care of stale entries.
  891. // https://github.com/gorhill/uMatrix/issues/540
  892. // Use only weak references to hold onto browser references.
  893. var browserToTabIdMap = new WeakMap();
  894. var tabIdToBrowserMap = new Map();
  895. var tabIdGenerator = 1;
  896. var indexFromBrowser = function(browser) {
  897. if ( !browser ) {
  898. return -1;
  899. }
  900. var win = getOwnerWindow(browser);
  901. if ( !win ) {
  902. return -1;
  903. }
  904. var tabBrowser = getTabBrowser(win);
  905. if ( tabBrowser === null ) {
  906. return -1;
  907. }
  908. // This can happen, for example, the `view-source:` window, there is
  909. // no tabbrowser object, the browser object sits directly in the
  910. // window.
  911. if ( tabBrowser === browser ) {
  912. return 0;
  913. }
  914. return tabBrowser.browsers.indexOf(browser);
  915. };
  916. var indexFromTarget = function(target) {
  917. return indexFromBrowser(browserFromTarget(target));
  918. };
  919. var tabFromBrowser = function(browser) {
  920. var i = indexFromBrowser(browser);
  921. if ( i === -1 ) {
  922. return null;
  923. }
  924. var win = getOwnerWindow(browser);
  925. if ( !win ) {
  926. return null;
  927. }
  928. var tabBrowser = getTabBrowser(win);
  929. if ( tabBrowser === null ) {
  930. return null;
  931. }
  932. if ( !tabBrowser.tabs || i >= tabBrowser.tabs.length ) {
  933. return null;
  934. }
  935. return tabBrowser.tabs[i];
  936. };
  937. var browserFromTarget = function(target) {
  938. if ( !target ) {
  939. return null;
  940. }
  941. if ( target.linkedPanel ) { // target is a tab
  942. target = target.linkedBrowser;
  943. }
  944. if ( target.localName !== 'browser' ) {
  945. return null;
  946. }
  947. return target;
  948. };
  949. var tabIdFromTarget = function(target) {
  950. var browser = browserFromTarget(target);
  951. if ( browser === null ) {
  952. return vAPI.noTabId;
  953. }
  954. var tabId = browserToTabIdMap.get(browser);
  955. if ( tabId === undefined ) {
  956. tabId = '' + tabIdGenerator++;
  957. browserToTabIdMap.set(browser, tabId);
  958. tabIdToBrowserMap.set(tabId, Cu.getWeakReference(browser));
  959. }
  960. return tabId;
  961. };
  962. var browserFromTabId = function(tabId) {
  963. var weakref = tabIdToBrowserMap.get(tabId);
  964. var browser = weakref && weakref.get();
  965. return browser || null;
  966. };
  967. var currentBrowser = function() {
  968. var win = winWatcher.getCurrentWindow();
  969. // https://github.com/gorhill/uBlock/issues/399
  970. // getTabBrowser() can return null at browser launch time.
  971. var tabBrowser = getTabBrowser(win);
  972. if ( tabBrowser === null ) {
  973. return null;
  974. }
  975. return browserFromTarget(tabBrowser.selectedTab);
  976. };
  977. var removeBrowserEntry = function(tabId, browser) {
  978. if ( tabId && tabId !== vAPI.noTabId ) {
  979. vAPI.tabs.onClosed(tabId);
  980. delete vAPI.toolbarButton.tabs[tabId];
  981. tabIdToBrowserMap.delete(tabId);
  982. }
  983. if ( browser ) {
  984. browserToTabIdMap.delete(browser);
  985. }
  986. };
  987. var removeTarget = function(target) {
  988. onClose({ target: target });
  989. };
  990. var getAllBrowsers = function() {
  991. var browsers = [], browser;
  992. for ( var [tabId, weakref] of tabIdToBrowserMap ) {
  993. browser = weakref.get();
  994. // TODO:
  995. // Maybe call removeBrowserEntry() if the browser no longer exists?
  996. if ( browser ) {
  997. browsers.push(browser);
  998. }
  999. }
  1000. return browsers;
  1001. };
  1002. // https://developer.mozilla.org/en-US/docs/Web/Events/TabOpen
  1003. //var onOpen = function({target}) {
  1004. // var tabId = tabIdFromTarget(target);
  1005. // var browser = browserFromTabId(tabId);
  1006. // vAPI.tabs.onNavigation({
  1007. // frameId: 0,
  1008. // tabId: tabId,
  1009. // url: browser.currentURI.asciiSpec,
  1010. // });
  1011. //};
  1012. // https://developer.mozilla.org/en-US/docs/Web/Events/TabShow
  1013. var onShow = function({target}) {
  1014. tabIdFromTarget(target);
  1015. };
  1016. // https://developer.mozilla.org/en-US/docs/Web/Events/TabClose
  1017. var onClose = function({target}) {
  1018. // target is tab in Firefox, browser in Fennec
  1019. var browser = browserFromTarget(target);
  1020. var tabId = browserToTabIdMap.get(browser);
  1021. removeBrowserEntry(tabId, browser);
  1022. };
  1023. // https://developer.mozilla.org/en-US/docs/Web/Events/TabSelect
  1024. // This is an entry point: when creating a new tab, it is not always
  1025. // reported through onLocationChanged... Sigh. It is "reported" here
  1026. // however.
  1027. var onSelect = function({target}) {
  1028. var browser = browserFromTarget(target);
  1029. var tabId = browserToTabIdMap.get(browser);
  1030. if ( tabId === undefined ) {
  1031. tabId = tabIdFromTarget(target);
  1032. vAPI.tabs.onNavigation({
  1033. frameId: 0,
  1034. tabId: tabId,
  1035. url: browser.currentURI.asciiSpec
  1036. });
  1037. }
  1038. vAPI.setIcon(tabId, getOwnerWindow(target));
  1039. };
  1040. var locationChangedMessageName = location.host + ':locationChanged';
  1041. var onLocationChanged = function(e) {
  1042. var vapi = vAPI;
  1043. var details = e.data;
  1044. // Ignore notifications related to our popup
  1045. if ( details.url.lastIndexOf(vapi.getURL('popup.html'), 0) === 0 ) {
  1046. return;
  1047. }
  1048. var browser = e.target;
  1049. var tabId = tabIdFromTarget(browser);
  1050. if ( tabId === vapi.noTabId ) {
  1051. return;
  1052. }
  1053. // LOCATION_CHANGE_SAME_DOCUMENT = "did not load a new document"
  1054. if ( details.flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT ) {
  1055. vapi.tabs.onUpdated(tabId, {url: details.url}, {
  1056. frameId: 0,
  1057. tabId: tabId,
  1058. url: browser.currentURI.asciiSpec
  1059. });
  1060. return;
  1061. }
  1062. // https://github.com/chrisaljoudi/uBlock/issues/105
  1063. // Allow any kind of pages
  1064. vapi.tabs.onNavigation({
  1065. frameId: 0,
  1066. tabId: tabId,
  1067. url: details.url
  1068. });
  1069. };
  1070. var attachToTabBrowser = function(window) {
  1071. if ( typeof vAPI.toolbarButton.attachToNewWindow === 'function' ) {
  1072. vAPI.toolbarButton.attachToNewWindow(window);
  1073. }
  1074. var tabBrowser = getTabBrowser(window);
  1075. if ( tabBrowser === null ) {
  1076. return;
  1077. }
  1078. var tabContainer;
  1079. if ( tabBrowser.deck ) { // Fennec
  1080. tabContainer = tabBrowser.deck;
  1081. } else if ( tabBrowser.tabContainer ) { // Firefox
  1082. tabContainer = tabBrowser.tabContainer;
  1083. vAPI.contextMenu.register(document);
  1084. }
  1085. // https://github.com/gorhill/uBlock/issues/697
  1086. // Ignore `TabShow` events: unfortunately the `pending` attribute is
  1087. // not set when a tab is opened as a result of session restore -- it is
  1088. // set *after* the event is fired in such case.
  1089. if ( tabContainer ) {
  1090. tabContainer.addEventListener('TabShow', onShow);
  1091. tabContainer.addEventListener('TabClose', onClose);
  1092. // when new window is opened TabSelect doesn't run on the selected tab?
  1093. tabContainer.addEventListener('TabSelect', onSelect);
  1094. }
  1095. };
  1096. // https://github.com/gorhill/uBlock/issues/906
  1097. // Ensure the environment is ready before trying to attaching.
  1098. var canAttachToTabBrowser = function(window) {
  1099. var document = window && window.document;
  1100. if ( !document || document.readyState !== 'complete' ) {
  1101. return false;
  1102. }
  1103. // On some platforms, the tab browser isn't immediately available,
  1104. // try waiting a bit if this happens.
  1105. // https://github.com/gorhill/uBlock/issues/763
  1106. // Not getting a tab browser should not prevent from attaching ourself
  1107. // to the window.
  1108. var tabBrowser = getTabBrowser(window);
  1109. if ( tabBrowser === null ) {
  1110. return false;
  1111. }
  1112. return winWatcher.toBrowserWindow(window) !== null;
  1113. };
  1114. var onWindowLoad = function(win) {
  1115. deferUntil(
  1116. canAttachToTabBrowser.bind(null, win),
  1117. attachToTabBrowser.bind(null, win)
  1118. );
  1119. };
  1120. var onWindowUnload = function(win) {
  1121. vAPI.contextMenu.unregister(win.document);
  1122. var tabBrowser = getTabBrowser(win);
  1123. if ( tabBrowser === null ) {
  1124. return;
  1125. }
  1126. var tabContainer = tabBrowser.tabContainer;
  1127. if ( tabContainer ) {
  1128. tabContainer.removeEventListener('TabShow', onShow);
  1129. tabContainer.removeEventListener('TabClose', onClose);
  1130. tabContainer.removeEventListener('TabSelect', onSelect);
  1131. }
  1132. // https://github.com/gorhill/uBlock/issues/574
  1133. // To keep in mind: not all windows are tab containers,
  1134. // sometimes the window IS the tab.
  1135. var tabs;
  1136. if ( tabBrowser.tabs ) {
  1137. tabs = tabBrowser.tabs;
  1138. } else if ( tabBrowser.localName === 'browser' ) {
  1139. tabs = [tabBrowser];
  1140. } else {
  1141. tabs = [];
  1142. }
  1143. var browser, URI, tabId;
  1144. var tabindex = tabs.length, tab;
  1145. while ( tabindex-- ) {
  1146. tab = tabs[tabindex];
  1147. browser = browserFromTarget(tab);
  1148. if ( browser === null ) {
  1149. continue;
  1150. }
  1151. URI = browser.currentURI;
  1152. // Close extension tabs
  1153. if ( URI.schemeIs('chrome') && URI.host === location.host ) {
  1154. vAPI.tabs._remove(tab, getTabBrowser(win));
  1155. }
  1156. tabId = browserToTabIdMap.get(browser);
  1157. if ( tabId !== undefined ) {
  1158. removeBrowserEntry(tabId, browser);
  1159. tabIdToBrowserMap.delete(tabId);
  1160. }
  1161. browserToTabIdMap.delete(browser);
  1162. }
  1163. };
  1164. // Initialize map with existing active tabs
  1165. var start = function() {
  1166. var tabBrowser, tabs, tab;
  1167. for ( var win of winWatcher.getWindows() ) {
  1168. onWindowLoad(win);
  1169. tabBrowser = getTabBrowser(win);
  1170. if ( tabBrowser === null ) {
  1171. continue;
  1172. }
  1173. for ( tab of tabBrowser.tabs ) {
  1174. if ( !tab.hasAttribute('pending') ) {
  1175. tabIdFromTarget(tab);
  1176. }
  1177. }
  1178. }
  1179. winWatcher.onOpenWindow = onWindowLoad;
  1180. winWatcher.onCloseWindow = onWindowUnload;
  1181. vAPI.messaging.globalMessageManager.addMessageListener(
  1182. locationChangedMessageName,
  1183. onLocationChanged
  1184. );
  1185. };
  1186. var stop = function() {
  1187. winWatcher.onOpenWindow = null;
  1188. winWatcher.onCloseWindow = null;
  1189. vAPI.messaging.globalMessageManager.removeMessageListener(
  1190. locationChangedMessageName,
  1191. onLocationChanged
  1192. );
  1193. for ( var win of winWatcher.getWindows() ) {
  1194. onWindowUnload(win);
  1195. }
  1196. browserToTabIdMap = new WeakMap();
  1197. tabIdToBrowserMap.clear();
  1198. };
  1199. cleanupTasks.push(stop);
  1200. return {
  1201. browsers: getAllBrowsers,
  1202. browserFromTabId: browserFromTabId,
  1203. browserFromTarget: browserFromTarget,
  1204. currentBrowser: currentBrowser,
  1205. indexFromTarget: indexFromTarget,
  1206. removeTarget: removeTarget,
  1207. start: start,
  1208. tabFromBrowser: tabFromBrowser,
  1209. tabIdFromTarget: tabIdFromTarget
  1210. };
  1211. })();
  1212. /******************************************************************************/
  1213. vAPI.setIcon = function(tabId, iconId, badge) {
  1214. // If badge is undefined, then setIcon was called from the TabSelect event
  1215. var win;
  1216. if ( badge === undefined ) {
  1217. win = iconId;
  1218. } else {
  1219. win = winWatcher.getCurrentWindow();
  1220. }
  1221. var tabBrowser = getTabBrowser(win);
  1222. if ( tabBrowser === null ) {
  1223. return;
  1224. }
  1225. var curTabId = tabWatcher.tabIdFromTarget(tabBrowser.selectedTab);
  1226. var tb = vAPI.toolbarButton;
  1227. // from 'TabSelect' event
  1228. if ( tabId === undefined ) {
  1229. tabId = curTabId;
  1230. } else if ( badge !== undefined ) {
  1231. tb.tabs[tabId] = { badge: badge, img: iconId };
  1232. }
  1233. if ( tabId === curTabId ) {
  1234. tb.updateState(win, tabId);
  1235. }
  1236. };
  1237. /******************************************************************************/
  1238. vAPI.messaging = {
  1239. get globalMessageManager() {
  1240. return Cc['@mozilla.org/globalmessagemanager;1']
  1241. .getService(Ci.nsIMessageListenerManager);
  1242. },
  1243. frameScript: vAPI.getURL('frameScript.js'),
  1244. listeners: {},
  1245. defaultHandler: null,
  1246. NOOPFUNC: function(){},
  1247. UNHANDLED: 'vAPI.messaging.notHandled'
  1248. };
  1249. /******************************************************************************/
  1250. vAPI.messaging.listen = function(listenerName, callback) {
  1251. this.listeners[listenerName] = callback;
  1252. };
  1253. /******************************************************************************/
  1254. vAPI.messaging.onMessage = function({target, data}) {
  1255. var messageManager = target.messageManager;
  1256. if ( !messageManager ) {
  1257. // Message came from a popup, and its message manager is not usable.
  1258. // So instead we broadcast to the parent window.
  1259. messageManager = getOwnerWindow(
  1260. target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
  1261. ).messageManager;
  1262. }
  1263. var channelNameRaw = data.channelName;
  1264. var pos = channelNameRaw.indexOf('|');
  1265. var channelName = channelNameRaw.slice(pos + 1);
  1266. var callback = vAPI.messaging.NOOPFUNC;
  1267. if ( data.requestId !== undefined ) {
  1268. callback = CallbackWrapper.factory(
  1269. messageManager,
  1270. channelName,
  1271. channelNameRaw.slice(0, pos),
  1272. data.requestId
  1273. ).callback;
  1274. }
  1275. var sender = {
  1276. tab: {
  1277. id: tabWatcher.tabIdFromTarget(target)
  1278. }
  1279. };
  1280. // Specific handler
  1281. var r = vAPI.messaging.UNHANDLED;
  1282. var listener = vAPI.messaging.listeners[channelName];
  1283. if ( typeof listener === 'function' ) {
  1284. r = listener(data.msg, sender, callback);
  1285. }
  1286. if ( r !== vAPI.messaging.UNHANDLED ) {
  1287. return;
  1288. }
  1289. // Default handler
  1290. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  1291. if ( r !== vAPI.messaging.UNHANDLED ) {
  1292. return;
  1293. }
  1294. console.error('uMatrix> messaging > unknown request: %o', data);
  1295. // Unhandled:
  1296. // Need to callback anyways in case caller expected an answer, or
  1297. // else there is a memory leak on caller's side
  1298. callback();
  1299. };
  1300. /******************************************************************************/
  1301. vAPI.messaging.setup = function(defaultHandler) {
  1302. // Already setup?
  1303. if ( this.defaultHandler !== null ) {
  1304. return;
  1305. }
  1306. if ( typeof defaultHandler !== 'function' ) {
  1307. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  1308. }
  1309. this.defaultHandler = defaultHandler;
  1310. this.globalMessageManager.addMessageListener(
  1311. location.host + ':background',
  1312. this.onMessage
  1313. );
  1314. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  1315. cleanupTasks.push(function() {
  1316. var gmm = vAPI.messaging.globalMessageManager;
  1317. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  1318. gmm.removeMessageListener(
  1319. location.host + ':background',
  1320. vAPI.messaging.onMessage
  1321. );
  1322. });
  1323. };
  1324. /******************************************************************************/
  1325. vAPI.messaging.broadcast = function(message) {
  1326. this.globalMessageManager.broadcastAsyncMessage(
  1327. location.host + ':broadcast',
  1328. JSON.stringify({broadcast: true, msg: message})
  1329. );
  1330. };
  1331. /******************************************************************************/
  1332. // This allows to avoid creating a closure for every single message which
  1333. // expects an answer. Having a closure created each time a message is processed
  1334. // has been always bothering me. Another benefit of the implementation here
  1335. // is to reuse the callback proxy object, so less memory churning.
  1336. //
  1337. // https://developers.google.com/speed/articles/optimizing-javascript
  1338. // "Creating a closure is significantly slower then creating an inner
  1339. // function without a closure, and much slower than reusing a static
  1340. // function"
  1341. //
  1342. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  1343. // "the dreaded 'uniformly slow code' case where every function takes 1%
  1344. // of CPU and you have to make one hundred separate performance optimizations
  1345. // to improve performance at all"
  1346. //
  1347. // http://jsperf.com/closure-no-closure/2
  1348. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  1349. this.callback = this.proxy.bind(this); // bind once
  1350. this.init(messageManager, channelName, listenerId, requestId);
  1351. };
  1352. CallbackWrapper.junkyard = [];
  1353. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  1354. var wrapper = CallbackWrapper.junkyard.pop();
  1355. if ( wrapper ) {
  1356. wrapper.init(messageManager, channelName, listenerId, requestId);
  1357. return wrapper;
  1358. }
  1359. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  1360. };
  1361. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  1362. this.messageManager = messageManager;
  1363. this.channelName = channelName;
  1364. this.listenerId = listenerId;
  1365. this.requestId = requestId;
  1366. };
  1367. CallbackWrapper.prototype.proxy = function(response) {
  1368. var message = JSON.stringify({
  1369. requestId: this.requestId,
  1370. channelName: this.channelName,
  1371. msg: response !== undefined ? response : null
  1372. });
  1373. if ( this.messageManager.sendAsyncMessage ) {
  1374. this.messageManager.sendAsyncMessage(this.listenerId, message);
  1375. } else {
  1376. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  1377. }
  1378. // Mark for reuse
  1379. this.messageManager =
  1380. this.channelName =
  1381. this.requestId =
  1382. this.listenerId = null;
  1383. CallbackWrapper.junkyard.push(this);
  1384. };
  1385. /******************************************************************************/
  1386. var httpRequestHeadersFactory = function(channel) {
  1387. var entry = httpRequestHeadersFactory.junkyard.pop();
  1388. if ( entry ) {
  1389. return entry.init(channel);
  1390. }
  1391. return new HTTPRequestHeaders(channel);
  1392. };
  1393. httpRequestHeadersFactory.junkyard = [];
  1394. var HTTPRequestHeaders = function(channel) {
  1395. this.init(channel);
  1396. };
  1397. HTTPRequestHeaders.prototype.init = function(channel) {
  1398. this.channel = channel;
  1399. return this;
  1400. };
  1401. HTTPRequestHeaders.prototype.dispose = function() {
  1402. this.channel = null;
  1403. httpRequestHeadersFactory.junkyard.push(this);
  1404. };
  1405. HTTPRequestHeaders.prototype.getHeader = function(name) {
  1406. try {
  1407. return this.channel.getRequestHeader(name);
  1408. } catch (e) {
  1409. }
  1410. return '';
  1411. };
  1412. HTTPRequestHeaders.prototype.setHeader = function(name, newValue, create) {
  1413. var oldValue = this.getHeader(name);
  1414. if ( newValue === oldValue ) {
  1415. return false;
  1416. }
  1417. if ( oldValue === '' && create !== true ) {
  1418. return false;
  1419. }
  1420. this.channel.setRequestHeader(name, newValue, false);
  1421. return true;
  1422. };
  1423. /******************************************************************************/
  1424. var httpObserver = {
  1425. classDescription: 'net-channel-event-sinks for ' + location.host,
  1426. classID: Components.ID('{5d2e2797-6d68-42e2-8aeb-81ce6ba16b95}'),
  1427. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  1428. REQDATAKEY: location.host + 'reqdata',
  1429. ABORT: Components.results.NS_BINDING_ABORTED,
  1430. ACCEPT: Components.results.NS_SUCCEEDED,
  1431. // Request types:
  1432. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  1433. frameTypeMap: {
  1434. 6: 'main_frame',
  1435. 7: 'sub_frame'
  1436. },
  1437. typeMap: {
  1438. 1: 'other',
  1439. 2: 'script',
  1440. 3: 'image',
  1441. 4: 'stylesheet',
  1442. 5: 'object',
  1443. 6: 'main_frame',
  1444. 7: 'sub_frame',
  1445. 9: 'xbl',
  1446. 10: 'ping',
  1447. 11: 'xmlhttprequest',
  1448. 12: 'object',
  1449. 13: 'xml_dtd',
  1450. 14: 'font',
  1451. 15: 'media',
  1452. 16: 'websocket',
  1453. 17: 'csp_report',
  1454. 18: 'xslt',
  1455. 19: 'beacon',
  1456. 20: 'xmlhttprequest',
  1457. 21: 'imageset',
  1458. 22: 'web_manifest'
  1459. },
  1460. mimeTypeMap: {
  1461. 'audio': 15,
  1462. 'video': 15
  1463. },
  1464. get componentRegistrar() {
  1465. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  1466. },
  1467. get categoryManager() {
  1468. return Cc['@mozilla.org/categorymanager;1']
  1469. .getService(Ci.nsICategoryManager);
  1470. },
  1471. QueryInterface: (function() {
  1472. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  1473. return XPCOMUtils.generateQI([
  1474. Ci.nsIFactory,
  1475. Ci.nsIObserver,
  1476. Ci.nsIChannelEventSink,
  1477. Ci.nsISupportsWeakReference
  1478. ]);
  1479. })(),
  1480. createInstance: function(outer, iid) {
  1481. if ( outer ) {
  1482. throw Components.results.NS_ERROR_NO_AGGREGATION;
  1483. }
  1484. return this.QueryInterface(iid);
  1485. },
  1486. register: function() {
  1487. this.pendingRingBufferInit();
  1488. // https://developer.mozilla.org/en/docs/Observer_Notifications#HTTP_requests
  1489. Services.obs.addObserver(this, 'http-on-modify-request', true);
  1490. Services.obs.addObserver(this, 'http-on-examine-response', true);
  1491. Services.obs.addObserver(this, 'http-on-examine-cached-response', true);
  1492. // Guard against stale instances not having been unregistered
  1493. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  1494. try {
  1495. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  1496. } catch (ex) {
  1497. console.error('uMatrix> httpObserver > unable to unregister stale instance: ', ex);
  1498. }
  1499. }
  1500. this.componentRegistrar.registerFactory(
  1501. this.classID,
  1502. this.classDescription,
  1503. this.contractID,
  1504. this
  1505. );
  1506. this.categoryManager.addCategoryEntry(
  1507. 'net-channel-event-sinks',
  1508. this.contractID,
  1509. this.contractID,
  1510. false,
  1511. true
  1512. );
  1513. },
  1514. unregister: function() {
  1515. Services.obs.removeObserver(this, 'http-on-modify-request');
  1516. Services.obs.removeObserver(this, 'http-on-examine-response');
  1517. Services.obs.removeObserver(this, 'http-on-examine-cached-response');
  1518. this.componentRegistrar.unregisterFactory(this.classID, this);
  1519. this.categoryManager.deleteCategoryEntry(
  1520. 'net-channel-event-sinks',
  1521. this.contractID,
  1522. false
  1523. );
  1524. },
  1525. PendingRequest: function() {
  1526. this.rawType = 0;
  1527. this.tabId = 0;
  1528. this._key = ''; // key is url, from URI.spec
  1529. },
  1530. // If all work fine, this map should not grow indefinitely. It can have
  1531. // stale items in it, but these will be taken care of when entries in
  1532. // the ring buffer are overwritten.
  1533. pendingURLToIndex: new Map(),
  1534. pendingWritePointer: 0,
  1535. pendingRingBuffer: new Array(256),
  1536. pendingRingBufferInit: function() {
  1537. // Use and reuse pre-allocated PendingRequest objects = less memory
  1538. // churning.
  1539. var i = this.pendingRingBuffer.length;
  1540. while ( i-- ) {
  1541. this.pendingRingBuffer[i] = new this.PendingRequest();
  1542. }
  1543. },
  1544. // Pending request ring buffer:
  1545. // +-------+-------+-------+-------+-------+-------+-------
  1546. // |0 |1 |2 |3 |4 |5 |...
  1547. // +-------+-------+-------+-------+-------+-------+-------
  1548. //
  1549. // URL to ring buffer index map:
  1550. // { k = URL, s = ring buffer indices }
  1551. //
  1552. // s is a string which character codes map to ring buffer indices -- for
  1553. // when the same URL is received multiple times by shouldLoadListener()
  1554. // before the existing one is serviced by the network request observer.
  1555. // I believe the use of a string in lieu of an array reduces memory
  1556. // churning.
  1557. createPendingRequest: function(url) {
  1558. var bucket;
  1559. var i = this.pendingWritePointer;
  1560. this.pendingWritePointer = i + 1 & 255;
  1561. var preq = this.pendingRingBuffer[i];
  1562. var si = String.fromCharCode(i);
  1563. // Cleanup unserviced pending request
  1564. if ( preq._key !== '' ) {
  1565. bucket = this.pendingURLToIndex.get(preq._key);
  1566. if ( bucket.length === 1 ) {
  1567. this.pendingURLToIndex.delete(preq._key);
  1568. } else {
  1569. var pos = bucket.indexOf(si);
  1570. this.pendingURLToIndex.set(preq._key, bucket.slice(0, pos) + bucket.slice(pos + 1));
  1571. }
  1572. }
  1573. bucket = this.pendingURLToIndex.get(url);
  1574. this.pendingURLToIndex.set(url, bucket === undefined ? si : bucket + si);
  1575. preq._key = url;
  1576. return preq;
  1577. },
  1578. lookupPendingRequest: function(url) {
  1579. var bucket = this.pendingURLToIndex.get(url);
  1580. if ( bucket === undefined ) {
  1581. return null;
  1582. }
  1583. var i = bucket.charCodeAt(0);
  1584. if ( bucket.length === 1 ) {
  1585. this.pendingURLToIndex.delete(url);
  1586. } else {
  1587. this.pendingURLToIndex.set(url, bucket.slice(1));
  1588. }
  1589. var preq = this.pendingRingBuffer[i];
  1590. preq._key = ''; // mark as "serviced"
  1591. return preq;
  1592. },
  1593. handleRequest: function(channel, URI, tabId, rawType) {
  1594. var type = this.typeMap[rawType] || 'other';
  1595. var onBeforeRequest = vAPI.net.onBeforeRequest;
  1596. if ( onBeforeRequest.types === null || onBeforeRequest.types.has(type) ) {
  1597. var result = onBeforeRequest.callback({
  1598. parentFrameId: type === 'main_frame' ? -1 : 0,
  1599. tabId: tabId,
  1600. type: type,
  1601. url: URI.asciiSpec
  1602. });
  1603. if ( typeof result === 'object' ) {
  1604. channel.cancel(this.ABORT);
  1605. return true;
  1606. }
  1607. }
  1608. var onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders;
  1609. if ( onBeforeSendHeaders.types === null || onBeforeSendHeaders.types.has(type) ) {
  1610. var requestHeaders = httpRequestHeadersFactory(channel);
  1611. onBeforeSendHeaders.callback({
  1612. parentFrameId: type === 'main_frame' ? -1 : 0,
  1613. requestHeaders: requestHeaders,
  1614. tabId: tabId,
  1615. type: type,
  1616. url: URI.asciiSpec
  1617. });
  1618. requestHeaders.dispose();
  1619. }
  1620. return false;
  1621. },
  1622. channelDataFromChannel: function(channel) {
  1623. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  1624. try {
  1625. return channel.getProperty(this.REQDATAKEY) || null;
  1626. } catch (ex) {
  1627. }
  1628. }
  1629. return null;
  1630. },
  1631. // https://github.com/gorhill/uMatrix/issues/165
  1632. // https://developer.mozilla.org/en-US/Firefox/Releases/3.5/Updating_extensions#Getting_a_load_context_from_a_request
  1633. // Not sure `umatrix:shouldLoad` is still needed, uMatrix does not
  1634. // care about embedded frames topography.
  1635. // Also:
  1636. // https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Limitations_of_chrome_scripts
  1637. tabIdFromChannel: function(channel) {
  1638. var lc;
  1639. try {
  1640. lc = channel.notificationCallbacks.getInterface(Ci.nsILoadContext);
  1641. } catch(ex) {
  1642. }
  1643. if ( !lc ) {
  1644. try {
  1645. lc = channel.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext);
  1646. } catch(ex) {
  1647. }
  1648. if ( !lc ) {
  1649. return vAPI.noTabId;
  1650. }
  1651. }
  1652. if ( lc.topFrameElement ) {
  1653. return tabWatcher.tabIdFromTarget(lc.topFrameElement);
  1654. }
  1655. var win;
  1656. try {
  1657. win = lc.associatedWindow;
  1658. } catch (ex) { }
  1659. if ( !win ) {
  1660. return vAPI.noTabId;
  1661. }
  1662. if ( win.top ) {
  1663. win = win.top;
  1664. }
  1665. var tabBrowser;
  1666. try {
  1667. tabBrowser = getTabBrowser(
  1668. win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation)
  1669. .QueryInterface(Ci.nsIDocShell).rootTreeItem
  1670. .QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow)
  1671. );
  1672. } catch (ex) { }
  1673. if ( !tabBrowser ) {
  1674. return vAPI.noTabId;
  1675. }
  1676. if ( tabBrowser.getBrowserForContentWindow ) {
  1677. return tabWatcher.tabIdFromTarget(tabBrowser.getBrowserForContentWindow(win));
  1678. }
  1679. // Falling back onto _getTabForContentWindow to ensure older versions
  1680. // of Firefox work well.
  1681. return tabBrowser._getTabForContentWindow ?
  1682. tabWatcher.tabIdFromTarget(tabBrowser._getTabForContentWindow(win)) :
  1683. vAPI.noTabId;
  1684. },
  1685. rawtypeFromContentType: function(channel) {
  1686. var mime = channel.contentType;
  1687. if ( !mime ) {
  1688. return 0;
  1689. }
  1690. var pos = mime.indexOf('/');
  1691. if ( pos === -1 ) {
  1692. pos = mime.length;
  1693. }
  1694. return this.mimeTypeMap[mime.slice(0, pos)] || 0;
  1695. },
  1696. observe: function(channel, topic) {
  1697. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  1698. return;
  1699. }
  1700. var URI = channel.URI;
  1701. var channelData = this.channelDataFromChannel(channel);
  1702. if ( topic.lastIndexOf('http-on-examine-', 0) === 0 ) {
  1703. if ( channelData === null ) {
  1704. return;
  1705. }
  1706. var type = this.frameTypeMap[channelData[1]];
  1707. if ( !type ) {
  1708. return;
  1709. }
  1710. topic = 'Content-Security-Policy';
  1711. var result;
  1712. try {
  1713. result = channel.getResponseHeader(topic);
  1714. } catch (ex) {
  1715. result = null;
  1716. }
  1717. result = vAPI.net.onHeadersReceived.callback({
  1718. parentFrameId: type === 'main_frame' ? -1 : 0,
  1719. responseHeaders: result ? [{name: topic, value: result}] : [],
  1720. tabId: channelData[0],
  1721. type: type,
  1722. url: URI.asciiSpec
  1723. });
  1724. if ( result ) {
  1725. channel.setResponseHeader(
  1726. topic,
  1727. result.responseHeaders.pop().value,
  1728. true
  1729. );
  1730. }
  1731. return;
  1732. }
  1733. // http-on-modify-request
  1734. // The channel was previously serviced.
  1735. if ( channelData !== null ) {
  1736. this.handleRequest(channel, URI, channelData[0], channelData[1]);
  1737. return;
  1738. }
  1739. // The channel was never serviced.
  1740. var tabId;
  1741. var pendingRequest = this.lookupPendingRequest(URI.asciiSpec);
  1742. var rawType = 1;
  1743. var loadInfo = channel.loadInfo;
  1744. // https://github.com/gorhill/uMatrix/issues/390#issuecomment-155717004
  1745. if ( loadInfo ) {
  1746. rawType = loadInfo.externalContentPolicyType !== undefined ?
  1747. loadInfo.externalContentPolicyType :
  1748. loadInfo.contentPolicyType;
  1749. if ( !rawType ) {
  1750. rawType = 1;
  1751. }
  1752. }
  1753. if ( pendingRequest !== null ) {
  1754. tabId = pendingRequest.tabId;
  1755. // https://github.com/gorhill/uBlock/issues/654
  1756. // Use the request type from the HTTP observer point of view.
  1757. if ( rawType !== 1 ) {
  1758. pendingRequest.rawType = rawType;
  1759. } else {
  1760. rawType = pendingRequest.rawType;
  1761. }
  1762. } else {
  1763. tabId = this.tabIdFromChannel(channel);
  1764. }
  1765. if ( this.handleRequest(channel, URI, tabId, rawType) ) {
  1766. return;
  1767. }
  1768. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1769. return;
  1770. }
  1771. // Carry data for behind-the-scene redirects
  1772. channel.setProperty(this.REQDATAKEY, [tabId, rawType]);
  1773. },
  1774. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1775. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1776. // If error thrown, the redirect will fail
  1777. try {
  1778. var URI = newChannel.URI;
  1779. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1780. return;
  1781. }
  1782. if ( newChannel instanceof Ci.nsIWritablePropertyBag === false ) {
  1783. return;
  1784. }
  1785. var channelData = this.channelDataFromChannel(oldChannel);
  1786. if ( channelData === null ) {
  1787. return;
  1788. }
  1789. // Carry the data on in case of multiple redirects
  1790. newChannel.setProperty(this.REQDATAKEY, channelData);
  1791. } catch (ex) {
  1792. // console.error(ex);
  1793. } finally {
  1794. callback.onRedirectVerifyCallback(this.ACCEPT);
  1795. }
  1796. }
  1797. };
  1798. /******************************************************************************/
  1799. vAPI.net = {};
  1800. /******************************************************************************/
  1801. vAPI.net.registerListeners = function() {
  1802. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1803. new Set(this.onBeforeRequest.types) :
  1804. null;
  1805. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1806. new Set(this.onBeforeSendHeaders.types) :
  1807. null;
  1808. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  1809. var shouldLoadListener = function(e) {
  1810. var details = e.data;
  1811. var pendingReq = httpObserver.createPendingRequest(details.url);
  1812. pendingReq.rawType = details.rawType;
  1813. pendingReq.tabId = tabWatcher.tabIdFromTarget(e.target);
  1814. };
  1815. // https://github.com/gorhill/uMatrix/issues/200
  1816. // We need this only for Firefox 34 and less: the tab id is derived from
  1817. // the origin of the message.
  1818. if ( !vAPI.modernFirefox ) {
  1819. vAPI.messaging.globalMessageManager.addMessageListener(
  1820. shouldLoadListenerMessageName,
  1821. shouldLoadListener
  1822. );
  1823. }
  1824. httpObserver.register();
  1825. cleanupTasks.push(function() {
  1826. if ( !vAPI.modernFirefox ) {
  1827. vAPI.messaging.globalMessageManager.removeMessageListener(
  1828. shouldLoadListenerMessageName,
  1829. shouldLoadListener
  1830. );
  1831. }
  1832. httpObserver.unregister();
  1833. });
  1834. };
  1835. /******************************************************************************/
  1836. /******************************************************************************/
  1837. vAPI.toolbarButton = {
  1838. id: location.host + '-button',
  1839. type: 'view',
  1840. viewId: location.host + '-panel',
  1841. label: vAPI.app.name,
  1842. tooltiptext: vAPI.app.name,
  1843. tabs: {/*tabId: {badge: 0, img: boolean}*/},
  1844. init: null,
  1845. codePath: ''
  1846. };
  1847. /******************************************************************************/
  1848. // Non-Fennec: common code paths.
  1849. (function() {
  1850. if ( vAPI.fennec ) {
  1851. return;
  1852. }
  1853. var tbb = vAPI.toolbarButton;
  1854. var popupCommittedWidth = 0;
  1855. var popupCommittedHeight = 0;
  1856. tbb.onViewShowing = function({target}) {
  1857. popupCommittedWidth = popupCommittedHeight = 0;
  1858. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1859. };
  1860. tbb.onViewHiding = function({target}) {
  1861. target.parentNode.style.maxWidth = '';
  1862. target.firstChild.setAttribute('src', 'about:blank');
  1863. };
  1864. tbb.updateState = function(win, tabId) {
  1865. var button = win.document.getElementById(this.id);
  1866. if ( !button ) {
  1867. return;
  1868. }
  1869. var icon = this.tabs[tabId];
  1870. button.setAttribute('badge', icon && icon.badge || '');
  1871. button.classList.toggle('off', !icon || !icon.img);
  1872. var iconId = icon && icon.img ? icon.img : 'off';
  1873. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1874. button.style.listStyleImage = icon;
  1875. };
  1876. tbb.populatePanel = function(doc, panel) {
  1877. panel.setAttribute('id', this.viewId);
  1878. var iframe = doc.createElement('iframe');
  1879. iframe.setAttribute('type', 'content');
  1880. panel.appendChild(iframe);
  1881. var toPx = function(pixels) {
  1882. return pixels.toString() + 'px';
  1883. };
  1884. var scrollBarWidth = 0;
  1885. var resizeTimer = null;
  1886. var resizePopupDelayed = function(attempts) {
  1887. if ( resizeTimer !== null ) {
  1888. return false;
  1889. }
  1890. // Sanity check
  1891. attempts = (attempts || 0) + 1;
  1892. if ( attempts > 1/*000*/ ) {
  1893. //console.error('uMatrix> resizePopupDelayed: giving up after too many attempts');
  1894. return false;
  1895. }
  1896. resizeTimer = vAPI.setTimeout(resizePopup, 10, attempts);
  1897. return true;
  1898. };
  1899. var resizePopup = function(attempts) {
  1900. resizeTimer = null;
  1901. panel.parentNode.style.maxWidth = 'none';
  1902. var body = iframe.contentDocument.body;
  1903. // https://github.com/gorhill/uMatrix/issues/301
  1904. // Don't resize if committed size did not change.
  1905. if (
  1906. popupCommittedWidth === body.clientWidth &&
  1907. popupCommittedHeight === body.clientHeight
  1908. ) {
  1909. return;
  1910. }
  1911. // We set a limit for height
  1912. var height = Math.min(body.clientHeight, 600);
  1913. // https://github.com/chrisaljoudi/uBlock/issues/730
  1914. // Voodoo programming: this recipe works
  1915. panel.style.setProperty('height', toPx(height));
  1916. iframe.style.setProperty('height', toPx(height));
  1917. // Adjust width for presence/absence of vertical scroll bar which may
  1918. // have appeared as a result of last operation.
  1919. var contentWindow = iframe.contentWindow;
  1920. var width = body.clientWidth;
  1921. if ( contentWindow.scrollMaxY !== 0 ) {
  1922. width += scrollBarWidth;
  1923. }
  1924. panel.style.setProperty('width', toPx(width));
  1925. // scrollMaxX should always be zero once we know the scrollbar width
  1926. if ( contentWindow.scrollMaxX !== 0 ) {
  1927. scrollBarWidth = contentWindow.scrollMaxX;
  1928. width += scrollBarWidth;
  1929. panel.style.setProperty('width', toPx(width));
  1930. }
  1931. if ( iframe.clientHeight !== height || panel.clientWidth !== width ) {
  1932. if ( resizePopupDelayed(attempts) ) {
  1933. return;
  1934. }
  1935. // resizePopupDelayed won't be called again, so commit
  1936. // dimentsions.
  1937. }
  1938. popupCommittedWidth = body.clientWidth;
  1939. popupCommittedHeight = body.clientHeight;
  1940. };
  1941. var onResizeRequested = function() {
  1942. var body = iframe.contentDocument.body;
  1943. if ( body.getAttribute('data-resize-popup') !== 'true' ) {
  1944. return;
  1945. }
  1946. body.removeAttribute('data-resize-popup');
  1947. resizePopupDelayed();
  1948. };
  1949. var onPopupReady = function() {
  1950. var win = this.contentWindow;
  1951. if ( !win || win.location.host !== location.host ) {
  1952. return;
  1953. }
  1954. if ( typeof tbb.onBeforePopupReady === 'function' ) {
  1955. tbb.onBeforePopupReady.call(this);
  1956. }
  1957. resizePopupDelayed();
  1958. var body = win.document.body;
  1959. body.removeAttribute('data-resize-popup');
  1960. var mutationObserver = new win.MutationObserver(onResizeRequested);
  1961. mutationObserver.observe(body, {
  1962. attributes: true,
  1963. attributeFilter: [ 'data-resize-popup' ]
  1964. });
  1965. };
  1966. iframe.addEventListener('load', onPopupReady, true);
  1967. };
  1968. })();
  1969. /******************************************************************************/
  1970. // Firefox 28 and less
  1971. (function() {
  1972. var tbb = vAPI.toolbarButton;
  1973. if ( tbb.init !== null ) {
  1974. return;
  1975. }
  1976. var CustomizableUI = null;
  1977. var forceLegacyToolbarButton = vAPI.localStorage.getBool('forceLegacyToolbarButton');
  1978. if ( !forceLegacyToolbarButton ) {
  1979. try {
  1980. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1981. } catch (ex) {
  1982. }
  1983. }
  1984. if ( CustomizableUI !== null ) {
  1985. return;
  1986. }
  1987. tbb.codePath = 'legacy';
  1988. tbb.id = 'umatrix-legacy-button'; // NOTE: must match legacy-toolbar-button.css
  1989. tbb.viewId = tbb.id + '-panel';
  1990. var styleSheetUri = null;
  1991. var createToolbarButton = function(window) {
  1992. var document = window.document;
  1993. var toolbarButton = document.createElement('toolbarbutton');
  1994. toolbarButton.setAttribute('id', tbb.id);
  1995. // type = panel would be more accurate, but doesn't look as good
  1996. toolbarButton.setAttribute('type', 'menu');
  1997. toolbarButton.setAttribute('removable', 'true');
  1998. toolbarButton.setAttribute('class', 'toolbarbutton-1 chromeclass-toolbar-additional');
  1999. toolbarButton.setAttribute('label', tbb.label);
  2000. toolbarButton.setAttribute('tooltiptext', tbb.label);
  2001. var toolbarButtonPanel = document.createElement('panel');
  2002. // NOTE: Setting level to parent breaks the popup for PaleMoon under
  2003. // linux (mouse pointer misaligned with content). For some reason.
  2004. // toolbarButtonPanel.setAttribute('level', 'parent');
  2005. tbb.populatePanel(document, toolbarButtonPanel);
  2006. toolbarButtonPanel.addEventListener('popupshowing', tbb.onViewShowing);
  2007. toolbarButtonPanel.addEventListener('popuphiding', tbb.onViewHiding);
  2008. toolbarButton.appendChild(toolbarButtonPanel);
  2009. return toolbarButton;
  2010. };
  2011. var addLegacyToolbarButton = function(window) {
  2012. // uMatrix's stylesheet lazily added.
  2013. if ( styleSheetUri === null ) {
  2014. var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
  2015. .getService(Ci.nsIStyleSheetService);
  2016. styleSheetUri = Services.io.newURI(vAPI.getURL("css/legacy-toolbar-button.css"), null, null);
  2017. // Register global so it works in all windows, including palette
  2018. if ( !sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  2019. sss.loadAndRegisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  2020. }
  2021. }
  2022. var document = window.document;
  2023. // https://github.com/gorhill/uMatrix/issues/357
  2024. // Already installed?
  2025. if ( document.getElementById(tbb.id) !== null ) {
  2026. return;
  2027. }
  2028. var toolbox = document.getElementById('navigator-toolbox') ||
  2029. document.getElementById('mail-toolbox');
  2030. if ( toolbox === null ) {
  2031. return;
  2032. }
  2033. var toolbarButton = createToolbarButton(window);
  2034. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/toolbarpalette
  2035. var palette = toolbox.palette;
  2036. if ( palette && palette.querySelector('#' + tbb.id) === null ) {
  2037. palette.appendChild(toolbarButton);
  2038. }
  2039. // Find the place to put the button.
  2040. // Pale Moon: `toolbox.externalToolbars` can be undefined. Seen while
  2041. // testing popup test number 3:
  2042. // http://raymondhill.net/ublock/popup.html
  2043. var toolbars = toolbox.externalToolbars ? toolbox.externalToolbars.slice() : [];
  2044. for ( var child of toolbox.children ) {
  2045. if ( child.localName === 'toolbar' ) {
  2046. toolbars.push(child);
  2047. }
  2048. }
  2049. for ( var toolbar of toolbars ) {
  2050. var currentsetString = toolbar.getAttribute('currentset');
  2051. if ( !currentsetString ) {
  2052. continue;
  2053. }
  2054. var currentset = currentsetString.split(/\s*,\s*/);
  2055. var index = currentset.indexOf(tbb.id);
  2056. if ( index === -1 ) {
  2057. continue;
  2058. }
  2059. // This can occur with Pale Moon:
  2060. // "TypeError: toolbar.insertItem is not a function"
  2061. if ( typeof toolbar.insertItem !== 'function' ) {
  2062. continue;
  2063. }
  2064. // Found our button on this toolbar - but where on it?
  2065. var before = null;
  2066. for ( var i = index + 1; i < currentset.length; i++ ) {
  2067. before = toolbar.querySelector('[id="' + currentset[i] + '"]');
  2068. if ( before !== null ) {
  2069. break;
  2070. }
  2071. }
  2072. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Method/insertItem
  2073. toolbar.insertItem(tbb.id, before);
  2074. break;
  2075. }
  2076. // https://github.com/gorhill/uBlock/issues/763
  2077. // We are done if our toolbar button is already installed in one of the
  2078. // toolbar.
  2079. if ( palette !== null && toolbarButton.parentElement !== palette ) {
  2080. return;
  2081. }
  2082. // No button yet so give it a default location. If forcing the button,
  2083. // just put in in the palette rather than on any specific toolbar (who
  2084. // knows what toolbars will be available or visible!)
  2085. var navbar = document.getElementById('nav-bar');
  2086. if ( navbar !== null && !vAPI.localStorage.getBool('legacyToolbarButtonAdded') ) {
  2087. // https://github.com/gorhill/uBlock/issues/264
  2088. // Find a child customizable palette, if any.
  2089. navbar = navbar.querySelector('.customization-target') || navbar;
  2090. navbar.appendChild(toolbarButton);
  2091. navbar.setAttribute('currentset', navbar.currentSet);
  2092. document.persist(navbar.id, 'currentset');
  2093. vAPI.localStorage.setBool('legacyToolbarButtonAdded', 'true');
  2094. }
  2095. };
  2096. var canAddLegacyToolbarButton = function(window) {
  2097. var document = window.document;
  2098. if (
  2099. !document ||
  2100. document.readyState !== 'complete' ||
  2101. document.getElementById('nav-bar') === null
  2102. ) {
  2103. return false;
  2104. }
  2105. var toolbox = document.getElementById('navigator-toolbox') ||
  2106. document.getElementById('mail-toolbox');
  2107. return toolbox !== null && !!toolbox.palette;
  2108. };
  2109. var onPopupCloseRequested = function({target}) {
  2110. var document = target.ownerDocument;
  2111. if ( !document ) {
  2112. return;
  2113. }
  2114. var toolbarButtonPanel = document.getElementById(tbb.viewId);
  2115. if ( toolbarButtonPanel === null ) {
  2116. return;
  2117. }
  2118. // `hidePopup` reported as not existing while testing legacy button
  2119. // on FF 41.0.2.
  2120. // https://bugzilla.mozilla.org/show_bug.cgi?id=1151796
  2121. if ( typeof toolbarButtonPanel.hidePopup === 'function' ) {
  2122. toolbarButtonPanel.hidePopup();
  2123. }
  2124. };
  2125. var shutdown = function() {
  2126. for ( var win of winWatcher.getWindows() ) {
  2127. var toolbarButton = win.document.getElementById(tbb.id);
  2128. if ( toolbarButton ) {
  2129. toolbarButton.parentNode.removeChild(toolbarButton);
  2130. }
  2131. }
  2132. if ( styleSheetUri !== null ) {
  2133. var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
  2134. .getService(Ci.nsIStyleSheetService);
  2135. if ( sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  2136. sss.unregisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  2137. }
  2138. styleSheetUri = null;
  2139. }
  2140. vAPI.messaging.globalMessageManager.removeMessageListener(
  2141. location.host + ':closePopup',
  2142. onPopupCloseRequested
  2143. );
  2144. };
  2145. tbb.attachToNewWindow = function(win) {
  2146. deferUntil(
  2147. canAddLegacyToolbarButton.bind(null, win),
  2148. addLegacyToolbarButton.bind(null, win)
  2149. );
  2150. };
  2151. tbb.init = function() {
  2152. vAPI.messaging.globalMessageManager.addMessageListener(
  2153. location.host + ':closePopup',
  2154. onPopupCloseRequested
  2155. );
  2156. cleanupTasks.push(shutdown);
  2157. };
  2158. })();
  2159. /******************************************************************************/
  2160. // Firefox Australis < 36.
  2161. (function() {
  2162. var tbb = vAPI.toolbarButton;
  2163. if ( tbb.init !== null ) {
  2164. return;
  2165. }
  2166. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') >= 0 ) {
  2167. return null;
  2168. }
  2169. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  2170. return null;
  2171. }
  2172. var CustomizableUI = null;
  2173. try {
  2174. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  2175. } catch (ex) {
  2176. }
  2177. if ( CustomizableUI === null ) {
  2178. return;
  2179. }
  2180. tbb.codePath = 'australis';
  2181. tbb.CustomizableUI = CustomizableUI;
  2182. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  2183. var styleURI = null;
  2184. var onPopupCloseRequested = function({target}) {
  2185. if ( typeof tbb.closePopup === 'function' ) {
  2186. tbb.closePopup(target);
  2187. }
  2188. };
  2189. var shutdown = function() {
  2190. CustomizableUI.destroyWidget(tbb.id);
  2191. for ( var win of winWatcher.getWindows() ) {
  2192. var panel = win.document.getElementById(tbb.viewId);
  2193. panel.parentNode.removeChild(panel);
  2194. win.QueryInterface(Ci.nsIInterfaceRequestor)
  2195. .getInterface(Ci.nsIDOMWindowUtils)
  2196. .removeSheet(styleURI, 1);
  2197. }
  2198. vAPI.messaging.globalMessageManager.removeMessageListener(
  2199. location.host + ':closePopup',
  2200. onPopupCloseRequested
  2201. );
  2202. };
  2203. tbb.onBeforeCreated = function(doc) {
  2204. var panel = doc.createElement('panelview');
  2205. this.populatePanel(doc, panel);
  2206. doc.getElementById('PanelUI-multiView').appendChild(panel);
  2207. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  2208. .getInterface(Ci.nsIDOMWindowUtils)
  2209. .loadSheet(styleURI, 1);
  2210. };
  2211. tbb.onBeforePopupReady = function() {
  2212. // https://github.com/gorhill/uBlock/issues/83
  2213. // Add `portrait` class if width is constrained.
  2214. try {
  2215. this.contentDocument.body.classList.toggle(
  2216. 'portrait',
  2217. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  2218. );
  2219. } catch (ex) {
  2220. /* noop */
  2221. }
  2222. };
  2223. tbb.init = function() {
  2224. vAPI.messaging.globalMessageManager.addMessageListener(
  2225. location.host + ':closePopup',
  2226. onPopupCloseRequested
  2227. );
  2228. var style = [
  2229. '#' + this.id + '.off {',
  2230. 'list-style-image: url(',
  2231. vAPI.getURL('img/browsericons/icon19-off.png'),
  2232. ');',
  2233. '}',
  2234. '#' + this.id + ' {',
  2235. 'list-style-image: url(',
  2236. vAPI.getURL('img/browsericons/icon19.png'),
  2237. ');',
  2238. '}',
  2239. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  2240. 'width: 160px;',
  2241. 'height: 290px;',
  2242. 'overflow: hidden !important;',
  2243. '}',
  2244. '#' + this.id + '[badge]:not([badge=""])::after {',
  2245. 'position: absolute;',
  2246. 'margin-left: -16px;',
  2247. 'margin-top: 3px;',
  2248. 'padding: 1px 2px;',
  2249. 'font-size: 9px;',
  2250. 'font-weight: bold;',
  2251. 'color: #fff;',
  2252. 'background: #000;',
  2253. 'content: attr(badge);',
  2254. '}'
  2255. ];
  2256. styleURI = Services.io.newURI(
  2257. 'data:text/css,' + encodeURIComponent(style.join('')),
  2258. null,
  2259. null
  2260. );
  2261. this.closePopup = function(tabBrowser) {
  2262. CustomizableUI.hidePanelForNode(
  2263. tabBrowser.ownerDocument.getElementById(this.viewId)
  2264. );
  2265. };
  2266. CustomizableUI.createWidget(this);
  2267. cleanupTasks.push(shutdown);
  2268. };
  2269. })();
  2270. /******************************************************************************/
  2271. // Firefox Australis >= 36.
  2272. (function() {
  2273. var tbb = vAPI.toolbarButton;
  2274. if ( tbb.init !== null ) {
  2275. return;
  2276. }
  2277. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') < 0 ) {
  2278. return null;
  2279. }
  2280. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  2281. return null;
  2282. }
  2283. var CustomizableUI = null;
  2284. try {
  2285. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  2286. } catch (ex) {
  2287. }
  2288. if ( CustomizableUI === null ) {
  2289. return null;
  2290. }
  2291. tbb.codePath = 'australis';
  2292. tbb.CustomizableUI = CustomizableUI;
  2293. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  2294. var CUIEvents = {};
  2295. var badgeCSSRules = [
  2296. 'background: #000',
  2297. 'color: #fff'
  2298. ].join(';');
  2299. var updateBadgeStyle = function() {
  2300. for ( var win of winWatcher.getWindows() ) {
  2301. var button = win.document.getElementById(tbb.id);
  2302. if ( button === null ) {
  2303. continue;
  2304. }
  2305. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  2306. button,
  2307. 'class',
  2308. 'toolbarbutton-badge'
  2309. );
  2310. if ( !badge ) {
  2311. continue;
  2312. }
  2313. badge.style.cssText = badgeCSSRules;
  2314. }
  2315. };
  2316. var updateBadge = function() {
  2317. var wId = tbb.id;
  2318. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  2319. for ( var win of winWatcher.getWindows() ) {
  2320. var button = win.document.getElementById(wId);
  2321. if ( button === null ) {
  2322. continue;
  2323. }
  2324. if ( buttonInPanel ) {
  2325. button.classList.remove('badged-button');
  2326. continue;
  2327. }
  2328. button.classList.add('badged-button');
  2329. }
  2330. if ( buttonInPanel ) {
  2331. return;
  2332. }
  2333. // Anonymous elements need some time to be reachable
  2334. vAPI.setTimeout(updateBadgeStyle, 250);
  2335. }.bind(CUIEvents);
  2336. // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/CustomizableUI.jsm#Listeners
  2337. CUIEvents.onCustomizeEnd = updateBadge;
  2338. CUIEvents.onWidgetAdded = updateBadge;
  2339. CUIEvents.onWidgetUnderflow = updateBadge;
  2340. var onPopupCloseRequested = function({target}) {
  2341. if ( typeof tbb.closePopup === 'function' ) {
  2342. tbb.closePopup(target);
  2343. }
  2344. };
  2345. var shutdown = function() {
  2346. for ( var win of winWatcher.getWindows() ) {
  2347. var panel = win.document.getElementById(tbb.viewId);
  2348. if ( panel !== null && panel.parentNode !== null ) {
  2349. panel.parentNode.removeChild(panel);
  2350. }
  2351. win.QueryInterface(Ci.nsIInterfaceRequestor)
  2352. .getInterface(Ci.nsIDOMWindowUtils)
  2353. .removeSheet(styleURI, 1);
  2354. }
  2355. CustomizableUI.removeListener(CUIEvents);
  2356. CustomizableUI.destroyWidget(tbb.id);
  2357. vAPI.messaging.globalMessageManager.removeMessageListener(
  2358. location.host + ':closePopup',
  2359. onPopupCloseRequested
  2360. );
  2361. };
  2362. var styleURI = null;
  2363. tbb.onBeforeCreated = function(doc) {
  2364. var panel = doc.createElement('panelview');
  2365. this.populatePanel(doc, panel);
  2366. doc.getElementById('PanelUI-multiView').appendChild(panel);
  2367. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  2368. .getInterface(Ci.nsIDOMWindowUtils)
  2369. .loadSheet(styleURI, 1);
  2370. };
  2371. tbb.onCreated = function(button) {
  2372. button.setAttribute('badge', '');
  2373. vAPI.setTimeout(updateBadge, 250);
  2374. };
  2375. tbb.onBeforePopupReady = function() {
  2376. // https://github.com/gorhill/uBlock/issues/83
  2377. // Add `portrait` class if width is constrained.
  2378. try {
  2379. this.contentDocument.body.classList.toggle(
  2380. 'portrait',
  2381. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  2382. );
  2383. } catch (ex) {
  2384. /* noop */
  2385. }
  2386. };
  2387. tbb.closePopup = function(tabBrowser) {
  2388. CustomizableUI.hidePanelForNode(
  2389. tabBrowser.ownerDocument.getElementById(tbb.viewId)
  2390. );
  2391. };
  2392. tbb.init = function() {
  2393. vAPI.messaging.globalMessageManager.addMessageListener(
  2394. location.host + ':closePopup',
  2395. onPopupCloseRequested
  2396. );
  2397. CustomizableUI.addListener(CUIEvents);
  2398. var style = [
  2399. '#' + this.id + '.off {',
  2400. 'list-style-image: url(',
  2401. vAPI.getURL('img/browsericons/icon19-off.png'),
  2402. ');',
  2403. '}',
  2404. '#' + this.id + ' {',
  2405. 'list-style-image: url(',
  2406. vAPI.getURL('img/browsericons/icon19-19.png'),
  2407. ');',
  2408. '}',
  2409. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  2410. 'height: 290px;',
  2411. 'max-width: none !important;',
  2412. 'min-width: 0 !important;',
  2413. 'overflow: hidden !important;',
  2414. 'padding: 0 !important;',
  2415. 'width: 160px;',
  2416. '}'
  2417. ];
  2418. styleURI = Services.io.newURI(
  2419. 'data:text/css,' + encodeURIComponent(style.join('')),
  2420. null,
  2421. null
  2422. );
  2423. CustomizableUI.createWidget(this);
  2424. cleanupTasks.push(shutdown);
  2425. };
  2426. })();
  2427. /******************************************************************************/
  2428. // No toolbar button.
  2429. (function() {
  2430. // Just to ensure the number of cleanup tasks is as expected: toolbar
  2431. // button code is one single cleanup task regardless of platform.
  2432. if ( vAPI.toolbarButton.init === null ) {
  2433. cleanupTasks.push(function(){});
  2434. }
  2435. })();
  2436. /******************************************************************************/
  2437. if ( vAPI.toolbarButton.init !== null ) {
  2438. vAPI.toolbarButton.init();
  2439. }
  2440. /******************************************************************************/
  2441. /******************************************************************************/
  2442. vAPI.contextMenu = {
  2443. contextMap: {
  2444. frame: 'inFrame',
  2445. link: 'onLink',
  2446. image: 'onImage',
  2447. audio: 'onAudio',
  2448. video: 'onVideo',
  2449. editable: 'onEditableArea'
  2450. }
  2451. };
  2452. /******************************************************************************/
  2453. vAPI.contextMenu.displayMenuItem = function({target}) {
  2454. var doc = target.ownerDocument;
  2455. var gContextMenu = doc.defaultView.gContextMenu;
  2456. if ( !gContextMenu.browser ) {
  2457. return;
  2458. }
  2459. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  2460. var currentURI = gContextMenu.browser.currentURI;
  2461. // https://github.com/chrisaljoudi/uBlock/issues/105
  2462. // TODO: Should the element picker works on any kind of pages?
  2463. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  2464. menuitem.setAttribute('hidden', true);
  2465. return;
  2466. }
  2467. var ctx = vAPI.contextMenu.contexts;
  2468. if ( !ctx ) {
  2469. menuitem.setAttribute('hidden', false);
  2470. return;
  2471. }
  2472. var ctxMap = vAPI.contextMenu.contextMap;
  2473. for ( var context of ctx ) {
  2474. if (
  2475. context === 'page' &&
  2476. !gContextMenu.onLink &&
  2477. !gContextMenu.onImage &&
  2478. !gContextMenu.onEditableArea &&
  2479. !gContextMenu.inFrame &&
  2480. !gContextMenu.onVideo &&
  2481. !gContextMenu.onAudio
  2482. ) {
  2483. menuitem.setAttribute('hidden', false);
  2484. return;
  2485. }
  2486. if (
  2487. ctxMap.hasOwnProperty(context) &&
  2488. gContextMenu[ctxMap[context]]
  2489. ) {
  2490. menuitem.setAttribute('hidden', false);
  2491. return;
  2492. }
  2493. }
  2494. menuitem.setAttribute('hidden', true);
  2495. };
  2496. /******************************************************************************/
  2497. vAPI.contextMenu.register = (function() {
  2498. var register = function(doc) {
  2499. if ( !this.menuItemId ) {
  2500. return;
  2501. }
  2502. // Already installed?
  2503. if ( doc.getElementById(this.menuItemId) !== null ) {
  2504. return;
  2505. }
  2506. var contextMenu = doc.getElementById('contentAreaContextMenu');
  2507. var menuitem = doc.createElement('menuitem');
  2508. menuitem.setAttribute('id', this.menuItemId);
  2509. menuitem.setAttribute('label', this.menuLabel);
  2510. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  2511. menuitem.setAttribute('class', 'menuitem-iconic');
  2512. menuitem.addEventListener('command', this.onCommand);
  2513. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  2514. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  2515. };
  2516. // https://github.com/gorhill/uBlock/issues/906
  2517. // Be sure document.readyState is 'complete': it could happen at launch
  2518. // time that we are called by vAPI.contextMenu.create() directly before
  2519. // the environment is properly initialized.
  2520. var registerSafely = function(doc, tryCount) {
  2521. if ( doc.readyState === 'complete' ) {
  2522. register.call(this, doc);
  2523. return;
  2524. }
  2525. if ( typeof tryCount !== 'number' ) {
  2526. tryCount = 0;
  2527. }
  2528. tryCount += 1;
  2529. if ( tryCount < 8 ) {
  2530. vAPI.setTimeout(registerSafely.bind(this, doc, tryCount), 200);
  2531. }
  2532. };
  2533. return registerSafely;
  2534. })();
  2535. /******************************************************************************/
  2536. vAPI.contextMenu.unregister = function(doc) {
  2537. if ( !this.menuItemId ) {
  2538. return;
  2539. }
  2540. var menuitem = doc.getElementById(this.menuItemId);
  2541. if ( menuitem === null ) {
  2542. return;
  2543. }
  2544. var contextMenu = menuitem.parentNode;
  2545. menuitem.removeEventListener('command', this.onCommand);
  2546. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  2547. contextMenu.removeChild(menuitem);
  2548. };
  2549. /******************************************************************************/
  2550. vAPI.contextMenu.create = function(details, callback) {
  2551. this.menuItemId = details.id;
  2552. this.menuLabel = details.title;
  2553. this.contexts = details.contexts;
  2554. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  2555. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  2556. } else {
  2557. // default in Chrome
  2558. this.contexts = ['page'];
  2559. }
  2560. this.onCommand = function() {
  2561. var gContextMenu = getOwnerWindow(this).gContextMenu;
  2562. var details = {
  2563. menuItemId: this.id
  2564. };
  2565. if ( gContextMenu.inFrame ) {
  2566. details.tagName = 'iframe';
  2567. // Probably won't work with e10s
  2568. details.frameUrl = gContextMenu.focusedWindow.location.href;
  2569. } else if ( gContextMenu.onImage ) {
  2570. details.tagName = 'img';
  2571. details.srcUrl = gContextMenu.mediaURL;
  2572. } else if ( gContextMenu.onAudio ) {
  2573. details.tagName = 'audio';
  2574. details.srcUrl = gContextMenu.mediaURL;
  2575. } else if ( gContextMenu.onVideo ) {
  2576. details.tagName = 'video';
  2577. details.srcUrl = gContextMenu.mediaURL;
  2578. } else if ( gContextMenu.onLink ) {
  2579. details.tagName = 'a';
  2580. details.linkUrl = gContextMenu.linkURL;
  2581. }
  2582. callback(details, {
  2583. id: tabWatcher.tabIdFromTarget(gContextMenu.browser),
  2584. url: gContextMenu.browser.currentURI.asciiSpec
  2585. });
  2586. };
  2587. for ( var win of winWatcher.getWindows() ) {
  2588. this.register(win.document);
  2589. }
  2590. };
  2591. /******************************************************************************/
  2592. vAPI.contextMenu.remove = function() {
  2593. for ( var win of winWatcher.getWindows() ) {
  2594. this.unregister(win.document);
  2595. }
  2596. this.menuItemId = null;
  2597. this.menuLabel = null;
  2598. this.contexts = null;
  2599. this.onCommand = null;
  2600. };
  2601. /******************************************************************************/
  2602. /******************************************************************************/
  2603. var optionsObserver = (function() {
  2604. var addonId = 'uMatrix@raymondhill.net';
  2605. var commandHandler = function() {
  2606. switch ( this.id ) {
  2607. case 'showDashboardButton':
  2608. vAPI.tabs.open({ url: 'dashboard.html', index: -1 });
  2609. break;
  2610. case 'showLoggerButton':
  2611. vAPI.tabs.open({ url: 'logger-ui.html', index: -1 });
  2612. break;
  2613. default:
  2614. break;
  2615. }
  2616. };
  2617. var setupOptionsButton = function(doc, id) {
  2618. var button = doc.getElementById(id);
  2619. if ( button === null ) {
  2620. return;
  2621. }
  2622. button.addEventListener('command', commandHandler);
  2623. button.label = vAPI.i18n(id);
  2624. };
  2625. var setupOptionsButtons = function(doc) {
  2626. setupOptionsButton(doc, 'showDashboardButton');
  2627. setupOptionsButton(doc, 'showLoggerButton');
  2628. };
  2629. var observer = {
  2630. observe: function(doc, topic, id) {
  2631. if ( id !== addonId ) {
  2632. return;
  2633. }
  2634. setupOptionsButtons(doc);
  2635. }
  2636. };
  2637. // https://github.com/gorhill/uBlock/issues/948
  2638. // Older versions of Firefox can throw here when looking up `currentURI`.
  2639. var canInit = function() {
  2640. try {
  2641. var tabBrowser = tabWatcher.currentBrowser();
  2642. return tabBrowser &&
  2643. tabBrowser.currentURI &&
  2644. tabBrowser.currentURI.spec === 'about:addons' &&
  2645. tabBrowser.contentDocument &&
  2646. tabBrowser.contentDocument.readyState === 'complete';
  2647. } catch (ex) {
  2648. }
  2649. };
  2650. // Manually add the buttons if the `about:addons` page is already opened.
  2651. var init = function() {
  2652. if ( canInit() ) {
  2653. setupOptionsButtons(tabWatcher.currentBrowser().contentDocument);
  2654. }
  2655. };
  2656. var unregister = function() {
  2657. Services.obs.removeObserver(observer, 'addon-options-displayed');
  2658. };
  2659. var register = function() {
  2660. Services.obs.addObserver(observer, 'addon-options-displayed', false);
  2661. cleanupTasks.push(unregister);
  2662. deferUntil(canInit, init, { next: 463 });
  2663. };
  2664. return {
  2665. register: register,
  2666. unregister: unregister
  2667. };
  2668. })();
  2669. optionsObserver.register();
  2670. /******************************************************************************/
  2671. /******************************************************************************/
  2672. vAPI.lastError = function() {
  2673. return null;
  2674. };
  2675. /******************************************************************************/
  2676. /******************************************************************************/
  2677. // This is called only once, when everything has been loaded in memory after
  2678. // the extension was launched. It can be used to inject content scripts
  2679. // in already opened web pages, to remove whatever nuisance could make it to
  2680. // the web pages before uBlock was ready.
  2681. vAPI.onLoadAllCompleted = function() {
  2682. for ( var browser of tabWatcher.browsers() ) {
  2683. browser.messageManager.sendAsyncMessage(
  2684. location.host + '-load-completed'
  2685. );
  2686. }
  2687. };
  2688. /******************************************************************************/
  2689. /******************************************************************************/
  2690. // Likelihood is that we do not have to punycode: given punycode overhead,
  2691. // it's faster to check and skip than do it unconditionally all the time.
  2692. var punycodeHostname = punycode.toASCII;
  2693. var isNotASCII = /[^\x21-\x7F]/;
  2694. vAPI.punycodeHostname = function(hostname) {
  2695. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  2696. };
  2697. vAPI.punycodeURL = function(url) {
  2698. if ( isNotASCII.test(url) ) {
  2699. return Services.io.newURI(url, null, null).asciiSpec;
  2700. }
  2701. return url;
  2702. };
  2703. /******************************************************************************/
  2704. /******************************************************************************/
  2705. vAPI.cloud = (function() {
  2706. var extensionBranchPath = 'extensions.' + location.host;
  2707. var cloudBranchPath = extensionBranchPath + '.cloudStorage';
  2708. // https://github.com/gorhill/uBlock/issues/80#issuecomment-132081658
  2709. // We must use get/setComplexValue in order to properly handle strings
  2710. // with unicode characters.
  2711. var iss = Ci.nsISupportsString;
  2712. var argstr = Components.classes['@mozilla.org/supports-string;1']
  2713. .createInstance(iss);
  2714. var options = {
  2715. defaultDeviceName: '',
  2716. deviceName: ''
  2717. };
  2718. // User-supplied device name.
  2719. try {
  2720. options.deviceName = Services.prefs
  2721. .getBranch(extensionBranchPath + '.')
  2722. .getComplexValue('deviceName', iss)
  2723. .data;
  2724. } catch(ex) {
  2725. }
  2726. var getDefaultDeviceName = function() {
  2727. var name = '';
  2728. try {
  2729. name = Services.prefs
  2730. .getBranch('services.sync.client.')
  2731. .getComplexValue('name', iss)
  2732. .data;
  2733. } catch(ex) {
  2734. }
  2735. return name || window.navigator.platform || window.navigator.oscpu;
  2736. };
  2737. var start = function(dataKeys) {
  2738. var extensionBranch = Services.prefs.getBranch(extensionBranchPath + '.');
  2739. var syncBranch = Services.prefs.getBranch('services.sync.prefs.sync.');
  2740. // Mark config entries as syncable
  2741. argstr.data = '';
  2742. var dataKey;
  2743. for ( var i = 0; i < dataKeys.length; i++ ) {
  2744. dataKey = dataKeys[i];
  2745. if ( extensionBranch.prefHasUserValue('cloudStorage.' + dataKey) === false ) {
  2746. extensionBranch.setComplexValue('cloudStorage.' + dataKey, iss, argstr);
  2747. }
  2748. syncBranch.setBoolPref(cloudBranchPath + '.' + dataKey, true);
  2749. }
  2750. };
  2751. var push = function(datakey, data, callback) {
  2752. var branch = Services.prefs.getBranch(cloudBranchPath + '.');
  2753. var bin = {
  2754. 'source': options.deviceName || getDefaultDeviceName(),
  2755. 'tstamp': Date.now(),
  2756. 'data': data,
  2757. 'size': 0
  2758. };
  2759. bin.size = JSON.stringify(bin).length;
  2760. argstr.data = JSON.stringify(bin);
  2761. branch.setComplexValue(datakey, iss, argstr);
  2762. if ( typeof callback === 'function' ) {
  2763. callback();
  2764. }
  2765. };
  2766. var pull = function(datakey, callback) {
  2767. var result = null;
  2768. var branch = Services.prefs.getBranch(cloudBranchPath + '.');
  2769. try {
  2770. var json = branch.getComplexValue(datakey, iss).data;
  2771. if ( typeof json === 'string' ) {
  2772. result = JSON.parse(json);
  2773. }
  2774. } catch(ex) {
  2775. }
  2776. callback(result);
  2777. };
  2778. var getOptions = function(callback) {
  2779. if ( typeof callback !== 'function' ) {
  2780. return;
  2781. }
  2782. options.defaultDeviceName = getDefaultDeviceName();
  2783. callback(options);
  2784. };
  2785. var setOptions = function(details, callback) {
  2786. if ( typeof details !== 'object' || details === null ) {
  2787. return;
  2788. }
  2789. var branch = Services.prefs.getBranch(extensionBranchPath + '.');
  2790. if ( typeof details.deviceName === 'string' ) {
  2791. argstr.data = details.deviceName;
  2792. branch.setComplexValue('deviceName', iss, argstr);
  2793. options.deviceName = details.deviceName;
  2794. }
  2795. getOptions(callback);
  2796. };
  2797. return {
  2798. start: start,
  2799. push: push,
  2800. pull: pull,
  2801. getOptions: getOptions,
  2802. setOptions: setOptions
  2803. };
  2804. })();
  2805. /******************************************************************************/
  2806. /******************************************************************************/
  2807. vAPI.browserData = {};
  2808. /******************************************************************************/
  2809. // https://developer.mozilla.org/en-US/docs/HTTP_Cache
  2810. vAPI.browserData.clearCache = function(callback) {
  2811. // PURGE_DISK_DATA_ONLY:1
  2812. // PURGE_DISK_ALL:2
  2813. // PURGE_EVERYTHING:3
  2814. // However I verified that no argument does clear the cache data.
  2815. // There is no cache2 for older versions of Firefox.
  2816. if ( Services.cache2 ) {
  2817. Services.cache2.clear();
  2818. } else if ( Services.cache ) {
  2819. Services.cache.evictEntries(Services.cache.STORE_ON_DISK);
  2820. }
  2821. if ( typeof callback === 'function' ) {
  2822. callback();
  2823. }
  2824. };
  2825. /******************************************************************************/
  2826. vAPI.browserData.clearOrigin = function(/* domain */) {
  2827. // TODO
  2828. };
  2829. /******************************************************************************/
  2830. /******************************************************************************/
  2831. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager2
  2832. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  2833. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  2834. vAPI.cookies = {};
  2835. /******************************************************************************/
  2836. vAPI.cookies.CookieEntry = function(ffCookie) {
  2837. this.domain = ffCookie.host;
  2838. this.name = ffCookie.name;
  2839. this.path = ffCookie.path;
  2840. this.secure = ffCookie.isSecure === true;
  2841. this.session = ffCookie.expires === 0;
  2842. this.value = ffCookie.value;
  2843. };
  2844. /******************************************************************************/
  2845. vAPI.cookies.start = function() {
  2846. Services.obs.addObserver(this, 'cookie-changed', false);
  2847. Services.obs.addObserver(this, 'private-cookie-changed', false);
  2848. cleanupTasks.push(this.stop.bind(this));
  2849. };
  2850. /******************************************************************************/
  2851. vAPI.cookies.stop = function() {
  2852. Services.obs.removeObserver(this, 'cookie-changed');
  2853. Services.obs.removeObserver(this, 'private-cookie-changed');
  2854. };
  2855. /******************************************************************************/
  2856. vAPI.cookies.observe = function(subject, topic, reason) {
  2857. //if ( topic !== 'cookie-changed' && topic !== 'private-cookie-changed' ) {
  2858. // return;
  2859. //}
  2860. //
  2861. if ( reason === 'cleared' && typeof this.onAllRemoved === 'function' ) {
  2862. this.onAllRemoved();
  2863. return;
  2864. }
  2865. if ( subject === null ) {
  2866. return;
  2867. }
  2868. if ( subject instanceof Ci.nsICookie2 === false ) {
  2869. try {
  2870. subject = subject.QueryInterface(Ci.nsICookie2);
  2871. } catch (ex) {
  2872. return;
  2873. }
  2874. }
  2875. if ( reason === 'deleted' ) {
  2876. if ( typeof this.onRemoved === 'function' ) {
  2877. this.onRemoved(new this.CookieEntry(subject));
  2878. }
  2879. return;
  2880. }
  2881. if ( typeof this.onChanged === 'function' ) {
  2882. this.onChanged(new this.CookieEntry(subject));
  2883. }
  2884. };
  2885. /******************************************************************************/
  2886. // Meant and expected to be asynchronous.
  2887. vAPI.cookies.getAll = function(callback) {
  2888. if ( typeof callback !== 'function' ) {
  2889. return;
  2890. }
  2891. var onAsync = function() {
  2892. var out = [];
  2893. var enumerator = Services.cookies.enumerator;
  2894. var ffcookie;
  2895. while ( enumerator.hasMoreElements() ) {
  2896. ffcookie = enumerator.getNext();
  2897. if ( ffcookie instanceof Ci.nsICookie ) {
  2898. out.push(new this.CookieEntry(ffcookie));
  2899. }
  2900. }
  2901. callback(out);
  2902. };
  2903. vAPI.setTimeout(onAsync.bind(this), 0);
  2904. };
  2905. /******************************************************************************/
  2906. vAPI.cookies.remove = function(details, callback) {
  2907. var uri = Services.io.newURI(details.url, null, null);
  2908. var cookies = Services.cookies;
  2909. cookies.remove(uri.asciiHost, details.name, uri.path, false, {});
  2910. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false, {});
  2911. if ( typeof callback === 'function' ) {
  2912. callback({
  2913. domain: uri.asciiHost,
  2914. name: details.name,
  2915. path: uri.path
  2916. });
  2917. }
  2918. };
  2919. /******************************************************************************/
  2920. /******************************************************************************/
  2921. })();
  2922. /******************************************************************************/