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.

3460 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
9 years ago
9 years ago
9 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. // Or simply .equals if we care about the fragment
  761. if ( URI.equalsExceptRef(browser.currentURI) === false ) {
  762. continue;
  763. }
  764. this.select(tab);
  765. // Update URL if fragment is different
  766. if ( URI.equals(browser.currentURI) === false ) {
  767. browser.loadURI(URI.asciiSpec);
  768. }
  769. return;
  770. }
  771. }
  772. if ( details.active === undefined ) {
  773. details.active = true;
  774. }
  775. if ( details.tabId ) {
  776. tab = tabWatcher.browserFromTabId(details.tabId);
  777. if ( tab ) {
  778. tabWatcher.browserFromTarget(tab).loadURI(details.url);
  779. return;
  780. }
  781. }
  782. // Open in a standalone window
  783. if ( details.popup === true ) {
  784. Services.ww.openWindow(
  785. self,
  786. details.url,
  787. null,
  788. 'location=1,menubar=1,personalbar=1,resizable=1,toolbar=1',
  789. null
  790. );
  791. return;
  792. }
  793. var win = winWatcher.getCurrentWindow();
  794. var tabBrowser = getTabBrowser(win);
  795. if ( tabBrowser === null ) {
  796. return;
  797. }
  798. if ( details.index === -1 ) {
  799. details.index = tabBrowser.browsers.indexOf(tabBrowser.selectedBrowser) + 1;
  800. }
  801. tab = tabBrowser.loadOneTab(details.url, { inBackground: !details.active });
  802. if ( details.index !== undefined ) {
  803. tabBrowser.moveTabTo(tab, details.index);
  804. }
  805. };
  806. /******************************************************************************/
  807. // Replace the URL of a tab. Noop if the tab does not exist.
  808. vAPI.tabs.replace = function(tabId, url) {
  809. var targetURL = url;
  810. // extension pages
  811. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  812. targetURL = vAPI.getURL(targetURL);
  813. }
  814. var browser = tabWatcher.browserFromTabId(tabId);
  815. if ( browser ) {
  816. browser.loadURI(targetURL);
  817. }
  818. };
  819. /******************************************************************************/
  820. vAPI.tabs._remove = function(tab, tabBrowser) {
  821. if ( tabBrowser ) {
  822. tabBrowser.removeTab(tab);
  823. }
  824. };
  825. /******************************************************************************/
  826. vAPI.tabs.remove = function(tabId) {
  827. var browser = tabWatcher.browserFromTabId(tabId);
  828. if ( !browser ) {
  829. return;
  830. }
  831. var tab = tabWatcher.tabFromBrowser(browser);
  832. if ( !tab ) {
  833. return;
  834. }
  835. this._remove(tab, getTabBrowser(getOwnerWindow(browser)));
  836. };
  837. /******************************************************************************/
  838. vAPI.tabs.reload = function(tabId) {
  839. var browser = tabWatcher.browserFromTabId(tabId);
  840. if ( !browser ) {
  841. return;
  842. }
  843. browser.webNavigation.reload(Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE);
  844. };
  845. /******************************************************************************/
  846. vAPI.tabs.select = function(tab) {
  847. if ( typeof tab !== 'object' ) {
  848. tab = tabWatcher.tabFromBrowser(tabWatcher.browserFromTabId(tab));
  849. }
  850. if ( !tab ) {
  851. return;
  852. }
  853. // https://github.com/gorhill/uBlock/issues/470
  854. var win = getOwnerWindow(tab);
  855. win.focus();
  856. var tabBrowser = getTabBrowser(win);
  857. if ( tabBrowser ) {
  858. tabBrowser.selectedTab = tab;
  859. }
  860. };
  861. /******************************************************************************/
  862. vAPI.tabs.injectScript = function(tabId, details, callback) {
  863. var browser = tabWatcher.browserFromTabId(tabId);
  864. if ( !browser ) {
  865. return;
  866. }
  867. if ( typeof details.file !== 'string' ) {
  868. return;
  869. }
  870. details.file = vAPI.getURL(details.file);
  871. browser.messageManager.sendAsyncMessage(
  872. location.host + ':broadcast',
  873. JSON.stringify({
  874. broadcast: true,
  875. channelName: 'vAPI',
  876. msg: {
  877. cmd: 'injectScript',
  878. details: details
  879. }
  880. })
  881. );
  882. if ( typeof callback === 'function' ) {
  883. vAPI.setTimeout(callback, 13);
  884. }
  885. };
  886. /******************************************************************************/
  887. var tabWatcher = (function() {
  888. // TODO: find out whether we need a janitor to take care of stale entries.
  889. // https://github.com/gorhill/uMatrix/issues/540
  890. // Use only weak references to hold onto browser references.
  891. var browserToTabIdMap = new WeakMap();
  892. var tabIdToBrowserMap = new Map();
  893. var tabIdGenerator = 1;
  894. var indexFromBrowser = function(browser) {
  895. if ( !browser ) {
  896. return -1;
  897. }
  898. var win = getOwnerWindow(browser);
  899. if ( !win ) {
  900. return -1;
  901. }
  902. var tabBrowser = getTabBrowser(win);
  903. if ( tabBrowser === null ) {
  904. return -1;
  905. }
  906. // This can happen, for example, the `view-source:` window, there is
  907. // no tabbrowser object, the browser object sits directly in the
  908. // window.
  909. if ( tabBrowser === browser ) {
  910. return 0;
  911. }
  912. return tabBrowser.browsers.indexOf(browser);
  913. };
  914. var indexFromTarget = function(target) {
  915. return indexFromBrowser(browserFromTarget(target));
  916. };
  917. var tabFromBrowser = function(browser) {
  918. var i = indexFromBrowser(browser);
  919. if ( i === -1 ) {
  920. return null;
  921. }
  922. var win = getOwnerWindow(browser);
  923. if ( !win ) {
  924. return null;
  925. }
  926. var tabBrowser = getTabBrowser(win);
  927. if ( tabBrowser === null ) {
  928. return null;
  929. }
  930. if ( !tabBrowser.tabs || i >= tabBrowser.tabs.length ) {
  931. return null;
  932. }
  933. return tabBrowser.tabs[i];
  934. };
  935. var browserFromTarget = function(target) {
  936. if ( !target ) {
  937. return null;
  938. }
  939. if ( target.linkedPanel ) { // target is a tab
  940. target = target.linkedBrowser;
  941. }
  942. if ( target.localName !== 'browser' ) {
  943. return null;
  944. }
  945. return target;
  946. };
  947. var tabIdFromTarget = function(target) {
  948. var browser = browserFromTarget(target);
  949. if ( browser === null ) {
  950. return vAPI.noTabId;
  951. }
  952. var tabId = browserToTabIdMap.get(browser);
  953. if ( tabId === undefined ) {
  954. tabId = '' + tabIdGenerator++;
  955. browserToTabIdMap.set(browser, tabId);
  956. tabIdToBrowserMap.set(tabId, Cu.getWeakReference(browser));
  957. }
  958. return tabId;
  959. };
  960. var browserFromTabId = function(tabId) {
  961. var weakref = tabIdToBrowserMap.get(tabId);
  962. var browser = weakref && weakref.get();
  963. return browser || null;
  964. };
  965. var currentBrowser = function() {
  966. var win = winWatcher.getCurrentWindow();
  967. // https://github.com/gorhill/uBlock/issues/399
  968. // getTabBrowser() can return null at browser launch time.
  969. var tabBrowser = getTabBrowser(win);
  970. if ( tabBrowser === null ) {
  971. return null;
  972. }
  973. return browserFromTarget(tabBrowser.selectedTab);
  974. };
  975. var removeBrowserEntry = function(tabId, browser) {
  976. if ( tabId && tabId !== vAPI.noTabId ) {
  977. vAPI.tabs.onClosed(tabId);
  978. delete vAPI.toolbarButton.tabs[tabId];
  979. tabIdToBrowserMap.delete(tabId);
  980. }
  981. if ( browser ) {
  982. browserToTabIdMap.delete(browser);
  983. }
  984. };
  985. var removeTarget = function(target) {
  986. onClose({ target: target });
  987. };
  988. var getAllBrowsers = function() {
  989. var browsers = [], browser;
  990. for ( var [tabId, weakref] of tabIdToBrowserMap ) {
  991. browser = weakref.get();
  992. // TODO:
  993. // Maybe call removeBrowserEntry() if the browser no longer exists?
  994. if ( browser ) {
  995. browsers.push(browser);
  996. }
  997. }
  998. return browsers;
  999. };
  1000. // https://developer.mozilla.org/en-US/docs/Web/Events/TabOpen
  1001. //var onOpen = function({target}) {
  1002. // var tabId = tabIdFromTarget(target);
  1003. // var browser = browserFromTabId(tabId);
  1004. // vAPI.tabs.onNavigation({
  1005. // frameId: 0,
  1006. // tabId: tabId,
  1007. // url: browser.currentURI.asciiSpec,
  1008. // });
  1009. //};
  1010. // https://developer.mozilla.org/en-US/docs/Web/Events/TabShow
  1011. var onShow = function({target}) {
  1012. tabIdFromTarget(target);
  1013. };
  1014. // https://developer.mozilla.org/en-US/docs/Web/Events/TabClose
  1015. var onClose = function({target}) {
  1016. // target is tab in Firefox, browser in Fennec
  1017. var browser = browserFromTarget(target);
  1018. var tabId = browserToTabIdMap.get(browser);
  1019. removeBrowserEntry(tabId, browser);
  1020. };
  1021. // https://developer.mozilla.org/en-US/docs/Web/Events/TabSelect
  1022. // This is an entry point: when creating a new tab, it is not always
  1023. // reported through onLocationChanged... Sigh. It is "reported" here
  1024. // however.
  1025. var onSelect = function({target}) {
  1026. var browser = browserFromTarget(target);
  1027. var tabId = browserToTabIdMap.get(browser);
  1028. if ( tabId === undefined ) {
  1029. tabId = tabIdFromTarget(target);
  1030. vAPI.tabs.onNavigation({
  1031. frameId: 0,
  1032. tabId: tabId,
  1033. url: browser.currentURI.asciiSpec
  1034. });
  1035. }
  1036. vAPI.setIcon(tabId, getOwnerWindow(target));
  1037. };
  1038. var locationChangedMessageName = location.host + ':locationChanged';
  1039. var onLocationChanged = function(e) {
  1040. var vapi = vAPI;
  1041. var details = e.data;
  1042. // Ignore notifications related to our popup
  1043. if ( details.url.lastIndexOf(vapi.getURL('popup.html'), 0) === 0 ) {
  1044. return;
  1045. }
  1046. var browser = e.target;
  1047. var tabId = tabIdFromTarget(browser);
  1048. if ( tabId === vapi.noTabId ) {
  1049. return;
  1050. }
  1051. // LOCATION_CHANGE_SAME_DOCUMENT = "did not load a new document"
  1052. if ( details.flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT ) {
  1053. vapi.tabs.onUpdated(tabId, {url: details.url}, {
  1054. frameId: 0,
  1055. tabId: tabId,
  1056. url: browser.currentURI.asciiSpec
  1057. });
  1058. return;
  1059. }
  1060. // https://github.com/chrisaljoudi/uBlock/issues/105
  1061. // Allow any kind of pages
  1062. vapi.tabs.onNavigation({
  1063. frameId: 0,
  1064. tabId: tabId,
  1065. url: details.url
  1066. });
  1067. };
  1068. var attachToTabBrowser = function(window) {
  1069. if ( typeof vAPI.toolbarButton.attachToNewWindow === 'function' ) {
  1070. vAPI.toolbarButton.attachToNewWindow(window);
  1071. }
  1072. var tabBrowser = getTabBrowser(window);
  1073. if ( tabBrowser === null ) {
  1074. return;
  1075. }
  1076. var tabContainer;
  1077. if ( tabBrowser.deck ) { // Fennec
  1078. tabContainer = tabBrowser.deck;
  1079. } else if ( tabBrowser.tabContainer ) { // Firefox
  1080. tabContainer = tabBrowser.tabContainer;
  1081. vAPI.contextMenu.register(document);
  1082. }
  1083. // https://github.com/gorhill/uBlock/issues/697
  1084. // Ignore `TabShow` events: unfortunately the `pending` attribute is
  1085. // not set when a tab is opened as a result of session restore -- it is
  1086. // set *after* the event is fired in such case.
  1087. if ( tabContainer ) {
  1088. tabContainer.addEventListener('TabShow', onShow);
  1089. tabContainer.addEventListener('TabClose', onClose);
  1090. // when new window is opened TabSelect doesn't run on the selected tab?
  1091. tabContainer.addEventListener('TabSelect', onSelect);
  1092. }
  1093. };
  1094. // https://github.com/gorhill/uBlock/issues/906
  1095. // Ensure the environment is ready before trying to attaching.
  1096. var canAttachToTabBrowser = function(window) {
  1097. var document = window && window.document;
  1098. if ( !document || document.readyState !== 'complete' ) {
  1099. return false;
  1100. }
  1101. // On some platforms, the tab browser isn't immediately available,
  1102. // try waiting a bit if this happens.
  1103. // https://github.com/gorhill/uBlock/issues/763
  1104. // Not getting a tab browser should not prevent from attaching ourself
  1105. // to the window.
  1106. var tabBrowser = getTabBrowser(window);
  1107. if ( tabBrowser === null ) {
  1108. return false;
  1109. }
  1110. return winWatcher.toBrowserWindow(window) !== null;
  1111. };
  1112. var onWindowLoad = function(win) {
  1113. deferUntil(
  1114. canAttachToTabBrowser.bind(null, win),
  1115. attachToTabBrowser.bind(null, win)
  1116. );
  1117. };
  1118. var onWindowUnload = function(win) {
  1119. vAPI.contextMenu.unregister(win.document);
  1120. var tabBrowser = getTabBrowser(win);
  1121. if ( tabBrowser === null ) {
  1122. return;
  1123. }
  1124. var tabContainer = tabBrowser.tabContainer;
  1125. if ( tabContainer ) {
  1126. tabContainer.removeEventListener('TabShow', onShow);
  1127. tabContainer.removeEventListener('TabClose', onClose);
  1128. tabContainer.removeEventListener('TabSelect', onSelect);
  1129. }
  1130. // https://github.com/gorhill/uBlock/issues/574
  1131. // To keep in mind: not all windows are tab containers,
  1132. // sometimes the window IS the tab.
  1133. var tabs;
  1134. if ( tabBrowser.tabs ) {
  1135. tabs = tabBrowser.tabs;
  1136. } else if ( tabBrowser.localName === 'browser' ) {
  1137. tabs = [tabBrowser];
  1138. } else {
  1139. tabs = [];
  1140. }
  1141. var browser, URI, tabId;
  1142. var tabindex = tabs.length, tab;
  1143. while ( tabindex-- ) {
  1144. tab = tabs[tabindex];
  1145. browser = browserFromTarget(tab);
  1146. if ( browser === null ) {
  1147. continue;
  1148. }
  1149. URI = browser.currentURI;
  1150. // Close extension tabs
  1151. if ( URI.schemeIs('chrome') && URI.host === location.host ) {
  1152. vAPI.tabs._remove(tab, getTabBrowser(win));
  1153. }
  1154. tabId = browserToTabIdMap.get(browser);
  1155. if ( tabId !== undefined ) {
  1156. removeBrowserEntry(tabId, browser);
  1157. tabIdToBrowserMap.delete(tabId);
  1158. }
  1159. browserToTabIdMap.delete(browser);
  1160. }
  1161. };
  1162. // Initialize map with existing active tabs
  1163. var start = function() {
  1164. var tabBrowser, tabs, tab;
  1165. for ( var win of winWatcher.getWindows() ) {
  1166. onWindowLoad(win);
  1167. tabBrowser = getTabBrowser(win);
  1168. if ( tabBrowser === null ) {
  1169. continue;
  1170. }
  1171. for ( tab of tabBrowser.tabs ) {
  1172. if ( !tab.hasAttribute('pending') ) {
  1173. tabIdFromTarget(tab);
  1174. }
  1175. }
  1176. }
  1177. winWatcher.onOpenWindow = onWindowLoad;
  1178. winWatcher.onCloseWindow = onWindowUnload;
  1179. vAPI.messaging.globalMessageManager.addMessageListener(
  1180. locationChangedMessageName,
  1181. onLocationChanged
  1182. );
  1183. };
  1184. var stop = function() {
  1185. winWatcher.onOpenWindow = null;
  1186. winWatcher.onCloseWindow = null;
  1187. vAPI.messaging.globalMessageManager.removeMessageListener(
  1188. locationChangedMessageName,
  1189. onLocationChanged
  1190. );
  1191. for ( var win of winWatcher.getWindows() ) {
  1192. onWindowUnload(win);
  1193. }
  1194. browserToTabIdMap = new WeakMap();
  1195. tabIdToBrowserMap.clear();
  1196. };
  1197. cleanupTasks.push(stop);
  1198. return {
  1199. browsers: getAllBrowsers,
  1200. browserFromTabId: browserFromTabId,
  1201. browserFromTarget: browserFromTarget,
  1202. currentBrowser: currentBrowser,
  1203. indexFromTarget: indexFromTarget,
  1204. removeTarget: removeTarget,
  1205. start: start,
  1206. tabFromBrowser: tabFromBrowser,
  1207. tabIdFromTarget: tabIdFromTarget
  1208. };
  1209. })();
  1210. /******************************************************************************/
  1211. vAPI.setIcon = function(tabId, iconId, badge) {
  1212. // If badge is undefined, then setIcon was called from the TabSelect event
  1213. var win;
  1214. if ( badge === undefined ) {
  1215. win = iconId;
  1216. } else {
  1217. win = winWatcher.getCurrentWindow();
  1218. }
  1219. var tabBrowser = getTabBrowser(win);
  1220. if ( tabBrowser === null ) {
  1221. return;
  1222. }
  1223. var curTabId = tabWatcher.tabIdFromTarget(tabBrowser.selectedTab);
  1224. var tb = vAPI.toolbarButton;
  1225. // from 'TabSelect' event
  1226. if ( tabId === undefined ) {
  1227. tabId = curTabId;
  1228. } else if ( badge !== undefined ) {
  1229. tb.tabs[tabId] = { badge: badge, img: iconId };
  1230. }
  1231. if ( tabId === curTabId ) {
  1232. tb.updateState(win, tabId);
  1233. }
  1234. };
  1235. /******************************************************************************/
  1236. vAPI.messaging = {
  1237. get globalMessageManager() {
  1238. return Cc['@mozilla.org/globalmessagemanager;1']
  1239. .getService(Ci.nsIMessageListenerManager);
  1240. },
  1241. frameScript: vAPI.getURL('frameScript.js'),
  1242. listeners: {},
  1243. defaultHandler: null,
  1244. NOOPFUNC: function(){},
  1245. UNHANDLED: 'vAPI.messaging.notHandled'
  1246. };
  1247. /******************************************************************************/
  1248. vAPI.messaging.listen = function(listenerName, callback) {
  1249. this.listeners[listenerName] = callback;
  1250. };
  1251. /******************************************************************************/
  1252. vAPI.messaging.onMessage = function({target, data}) {
  1253. var messageManager = target.messageManager;
  1254. if ( !messageManager ) {
  1255. // Message came from a popup, and its message manager is not usable.
  1256. // So instead we broadcast to the parent window.
  1257. messageManager = getOwnerWindow(
  1258. target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
  1259. ).messageManager;
  1260. }
  1261. var channelNameRaw = data.channelName;
  1262. var pos = channelNameRaw.indexOf('|');
  1263. var channelName = channelNameRaw.slice(pos + 1);
  1264. var callback = vAPI.messaging.NOOPFUNC;
  1265. if ( data.requestId !== undefined ) {
  1266. callback = CallbackWrapper.factory(
  1267. messageManager,
  1268. channelName,
  1269. channelNameRaw.slice(0, pos),
  1270. data.requestId
  1271. ).callback;
  1272. }
  1273. var sender = {
  1274. tab: {
  1275. id: tabWatcher.tabIdFromTarget(target)
  1276. }
  1277. };
  1278. // Specific handler
  1279. var r = vAPI.messaging.UNHANDLED;
  1280. var listener = vAPI.messaging.listeners[channelName];
  1281. if ( typeof listener === 'function' ) {
  1282. r = listener(data.msg, sender, callback);
  1283. }
  1284. if ( r !== vAPI.messaging.UNHANDLED ) {
  1285. return;
  1286. }
  1287. // Default handler
  1288. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  1289. if ( r !== vAPI.messaging.UNHANDLED ) {
  1290. return;
  1291. }
  1292. console.error('uMatrix> messaging > unknown request: %o', data);
  1293. // Unhandled:
  1294. // Need to callback anyways in case caller expected an answer, or
  1295. // else there is a memory leak on caller's side
  1296. callback();
  1297. };
  1298. /******************************************************************************/
  1299. vAPI.messaging.setup = function(defaultHandler) {
  1300. // Already setup?
  1301. if ( this.defaultHandler !== null ) {
  1302. return;
  1303. }
  1304. if ( typeof defaultHandler !== 'function' ) {
  1305. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  1306. }
  1307. this.defaultHandler = defaultHandler;
  1308. this.globalMessageManager.addMessageListener(
  1309. location.host + ':background',
  1310. this.onMessage
  1311. );
  1312. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  1313. cleanupTasks.push(function() {
  1314. var gmm = vAPI.messaging.globalMessageManager;
  1315. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  1316. gmm.removeMessageListener(
  1317. location.host + ':background',
  1318. vAPI.messaging.onMessage
  1319. );
  1320. });
  1321. };
  1322. /******************************************************************************/
  1323. vAPI.messaging.broadcast = function(message) {
  1324. this.globalMessageManager.broadcastAsyncMessage(
  1325. location.host + ':broadcast',
  1326. JSON.stringify({broadcast: true, msg: message})
  1327. );
  1328. };
  1329. /******************************************************************************/
  1330. // This allows to avoid creating a closure for every single message which
  1331. // expects an answer. Having a closure created each time a message is processed
  1332. // has been always bothering me. Another benefit of the implementation here
  1333. // is to reuse the callback proxy object, so less memory churning.
  1334. //
  1335. // https://developers.google.com/speed/articles/optimizing-javascript
  1336. // "Creating a closure is significantly slower then creating an inner
  1337. // function without a closure, and much slower than reusing a static
  1338. // function"
  1339. //
  1340. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  1341. // "the dreaded 'uniformly slow code' case where every function takes 1%
  1342. // of CPU and you have to make one hundred separate performance optimizations
  1343. // to improve performance at all"
  1344. //
  1345. // http://jsperf.com/closure-no-closure/2
  1346. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  1347. this.callback = this.proxy.bind(this); // bind once
  1348. this.init(messageManager, channelName, listenerId, requestId);
  1349. };
  1350. CallbackWrapper.junkyard = [];
  1351. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  1352. var wrapper = CallbackWrapper.junkyard.pop();
  1353. if ( wrapper ) {
  1354. wrapper.init(messageManager, channelName, listenerId, requestId);
  1355. return wrapper;
  1356. }
  1357. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  1358. };
  1359. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  1360. this.messageManager = messageManager;
  1361. this.channelName = channelName;
  1362. this.listenerId = listenerId;
  1363. this.requestId = requestId;
  1364. };
  1365. CallbackWrapper.prototype.proxy = function(response) {
  1366. var message = JSON.stringify({
  1367. requestId: this.requestId,
  1368. channelName: this.channelName,
  1369. msg: response !== undefined ? response : null
  1370. });
  1371. if ( this.messageManager.sendAsyncMessage ) {
  1372. this.messageManager.sendAsyncMessage(this.listenerId, message);
  1373. } else {
  1374. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  1375. }
  1376. // Mark for reuse
  1377. this.messageManager =
  1378. this.channelName =
  1379. this.requestId =
  1380. this.listenerId = null;
  1381. CallbackWrapper.junkyard.push(this);
  1382. };
  1383. /******************************************************************************/
  1384. var httpRequestHeadersFactory = function(channel) {
  1385. var entry = httpRequestHeadersFactory.junkyard.pop();
  1386. if ( entry ) {
  1387. return entry.init(channel);
  1388. }
  1389. return new HTTPRequestHeaders(channel);
  1390. };
  1391. httpRequestHeadersFactory.junkyard = [];
  1392. var HTTPRequestHeaders = function(channel) {
  1393. this.init(channel);
  1394. };
  1395. HTTPRequestHeaders.prototype.init = function(channel) {
  1396. this.channel = channel;
  1397. return this;
  1398. };
  1399. HTTPRequestHeaders.prototype.dispose = function() {
  1400. this.channel = null;
  1401. httpRequestHeadersFactory.junkyard.push(this);
  1402. };
  1403. HTTPRequestHeaders.prototype.getHeader = function(name) {
  1404. try {
  1405. return this.channel.getRequestHeader(name);
  1406. } catch (e) {
  1407. }
  1408. return '';
  1409. };
  1410. HTTPRequestHeaders.prototype.setHeader = function(name, newValue, create) {
  1411. var oldValue = this.getHeader(name);
  1412. if ( newValue === oldValue ) {
  1413. return false;
  1414. }
  1415. if ( oldValue === '' && create !== true ) {
  1416. return false;
  1417. }
  1418. this.channel.setRequestHeader(name, newValue, false);
  1419. return true;
  1420. };
  1421. /******************************************************************************/
  1422. var httpObserver = {
  1423. classDescription: 'net-channel-event-sinks for ' + location.host,
  1424. classID: Components.ID('{5d2e2797-6d68-42e2-8aeb-81ce6ba16b95}'),
  1425. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  1426. REQDATAKEY: location.host + 'reqdata',
  1427. ABORT: Components.results.NS_BINDING_ABORTED,
  1428. ACCEPT: Components.results.NS_SUCCEEDED,
  1429. // Request types:
  1430. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  1431. frameTypeMap: {
  1432. 6: 'main_frame',
  1433. 7: 'sub_frame'
  1434. },
  1435. typeMap: {
  1436. 1: 'other',
  1437. 2: 'script',
  1438. 3: 'image',
  1439. 4: 'stylesheet',
  1440. 5: 'object',
  1441. 6: 'main_frame',
  1442. 7: 'sub_frame',
  1443. 9: 'xbl',
  1444. 10: 'ping',
  1445. 11: 'xmlhttprequest',
  1446. 12: 'object',
  1447. 13: 'xml_dtd',
  1448. 14: 'font',
  1449. 15: 'media',
  1450. 16: 'websocket',
  1451. 17: 'csp_report',
  1452. 18: 'xslt',
  1453. 19: 'beacon',
  1454. 20: 'xmlhttprequest',
  1455. 21: 'imageset',
  1456. 22: 'web_manifest'
  1457. },
  1458. mimeTypeMap: {
  1459. 'audio': 15,
  1460. 'video': 15
  1461. },
  1462. get componentRegistrar() {
  1463. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  1464. },
  1465. get categoryManager() {
  1466. return Cc['@mozilla.org/categorymanager;1']
  1467. .getService(Ci.nsICategoryManager);
  1468. },
  1469. QueryInterface: (function() {
  1470. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  1471. return XPCOMUtils.generateQI([
  1472. Ci.nsIFactory,
  1473. Ci.nsIObserver,
  1474. Ci.nsIChannelEventSink,
  1475. Ci.nsISupportsWeakReference
  1476. ]);
  1477. })(),
  1478. createInstance: function(outer, iid) {
  1479. if ( outer ) {
  1480. throw Components.results.NS_ERROR_NO_AGGREGATION;
  1481. }
  1482. return this.QueryInterface(iid);
  1483. },
  1484. register: function() {
  1485. this.pendingRingBufferInit();
  1486. // https://developer.mozilla.org/en/docs/Observer_Notifications#HTTP_requests
  1487. Services.obs.addObserver(this, 'http-on-modify-request', true);
  1488. Services.obs.addObserver(this, 'http-on-examine-response', true);
  1489. Services.obs.addObserver(this, 'http-on-examine-cached-response', true);
  1490. // Guard against stale instances not having been unregistered
  1491. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  1492. try {
  1493. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  1494. } catch (ex) {
  1495. console.error('uMatrix> httpObserver > unable to unregister stale instance: ', ex);
  1496. }
  1497. }
  1498. this.componentRegistrar.registerFactory(
  1499. this.classID,
  1500. this.classDescription,
  1501. this.contractID,
  1502. this
  1503. );
  1504. this.categoryManager.addCategoryEntry(
  1505. 'net-channel-event-sinks',
  1506. this.contractID,
  1507. this.contractID,
  1508. false,
  1509. true
  1510. );
  1511. },
  1512. unregister: function() {
  1513. Services.obs.removeObserver(this, 'http-on-modify-request');
  1514. Services.obs.removeObserver(this, 'http-on-examine-response');
  1515. Services.obs.removeObserver(this, 'http-on-examine-cached-response');
  1516. this.componentRegistrar.unregisterFactory(this.classID, this);
  1517. this.categoryManager.deleteCategoryEntry(
  1518. 'net-channel-event-sinks',
  1519. this.contractID,
  1520. false
  1521. );
  1522. },
  1523. PendingRequest: function() {
  1524. this.rawType = 0;
  1525. this.tabId = 0;
  1526. this._key = ''; // key is url, from URI.spec
  1527. },
  1528. // If all work fine, this map should not grow indefinitely. It can have
  1529. // stale items in it, but these will be taken care of when entries in
  1530. // the ring buffer are overwritten.
  1531. pendingURLToIndex: new Map(),
  1532. pendingWritePointer: 0,
  1533. pendingRingBuffer: new Array(256),
  1534. pendingRingBufferInit: function() {
  1535. // Use and reuse pre-allocated PendingRequest objects = less memory
  1536. // churning.
  1537. var i = this.pendingRingBuffer.length;
  1538. while ( i-- ) {
  1539. this.pendingRingBuffer[i] = new this.PendingRequest();
  1540. }
  1541. },
  1542. // Pending request ring buffer:
  1543. // +-------+-------+-------+-------+-------+-------+-------
  1544. // |0 |1 |2 |3 |4 |5 |...
  1545. // +-------+-------+-------+-------+-------+-------+-------
  1546. //
  1547. // URL to ring buffer index map:
  1548. // { k = URL, s = ring buffer indices }
  1549. //
  1550. // s is a string which character codes map to ring buffer indices -- for
  1551. // when the same URL is received multiple times by shouldLoadListener()
  1552. // before the existing one is serviced by the network request observer.
  1553. // I believe the use of a string in lieu of an array reduces memory
  1554. // churning.
  1555. createPendingRequest: function(url) {
  1556. var bucket;
  1557. var i = this.pendingWritePointer;
  1558. this.pendingWritePointer = i + 1 & 255;
  1559. var preq = this.pendingRingBuffer[i];
  1560. var si = String.fromCharCode(i);
  1561. // Cleanup unserviced pending request
  1562. if ( preq._key !== '' ) {
  1563. bucket = this.pendingURLToIndex.get(preq._key);
  1564. if ( bucket.length === 1 ) {
  1565. this.pendingURLToIndex.delete(preq._key);
  1566. } else {
  1567. var pos = bucket.indexOf(si);
  1568. this.pendingURLToIndex.set(preq._key, bucket.slice(0, pos) + bucket.slice(pos + 1));
  1569. }
  1570. }
  1571. bucket = this.pendingURLToIndex.get(url);
  1572. this.pendingURLToIndex.set(url, bucket === undefined ? si : bucket + si);
  1573. preq._key = url;
  1574. return preq;
  1575. },
  1576. lookupPendingRequest: function(url) {
  1577. var bucket = this.pendingURLToIndex.get(url);
  1578. if ( bucket === undefined ) {
  1579. return null;
  1580. }
  1581. var i = bucket.charCodeAt(0);
  1582. if ( bucket.length === 1 ) {
  1583. this.pendingURLToIndex.delete(url);
  1584. } else {
  1585. this.pendingURLToIndex.set(url, bucket.slice(1));
  1586. }
  1587. var preq = this.pendingRingBuffer[i];
  1588. preq._key = ''; // mark as "serviced"
  1589. return preq;
  1590. },
  1591. handleRequest: function(channel, URI, tabId, rawType) {
  1592. var type = this.typeMap[rawType] || 'other';
  1593. var onBeforeRequest = vAPI.net.onBeforeRequest;
  1594. if ( onBeforeRequest.types === null || onBeforeRequest.types.has(type) ) {
  1595. var result = onBeforeRequest.callback({
  1596. parentFrameId: type === 'main_frame' ? -1 : 0,
  1597. tabId: tabId,
  1598. type: type,
  1599. url: URI.asciiSpec
  1600. });
  1601. if ( typeof result === 'object' ) {
  1602. channel.cancel(this.ABORT);
  1603. return true;
  1604. }
  1605. }
  1606. var onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders;
  1607. if ( onBeforeSendHeaders.types === null || onBeforeSendHeaders.types.has(type) ) {
  1608. var requestHeaders = httpRequestHeadersFactory(channel);
  1609. onBeforeSendHeaders.callback({
  1610. parentFrameId: type === 'main_frame' ? -1 : 0,
  1611. requestHeaders: requestHeaders,
  1612. tabId: tabId,
  1613. type: type,
  1614. url: URI.asciiSpec
  1615. });
  1616. requestHeaders.dispose();
  1617. }
  1618. return false;
  1619. },
  1620. channelDataFromChannel: function(channel) {
  1621. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  1622. try {
  1623. return channel.getProperty(this.REQDATAKEY) || null;
  1624. } catch (ex) {
  1625. }
  1626. }
  1627. return null;
  1628. },
  1629. // https://github.com/gorhill/uMatrix/issues/165
  1630. // https://developer.mozilla.org/en-US/Firefox/Releases/3.5/Updating_extensions#Getting_a_load_context_from_a_request
  1631. // Not sure `umatrix:shouldLoad` is still needed, uMatrix does not
  1632. // care about embedded frames topography.
  1633. // Also:
  1634. // https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Limitations_of_chrome_scripts
  1635. tabIdFromChannel: function(channel) {
  1636. var lc;
  1637. try {
  1638. lc = channel.notificationCallbacks.getInterface(Ci.nsILoadContext);
  1639. } catch(ex) {
  1640. }
  1641. if ( !lc ) {
  1642. try {
  1643. lc = channel.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext);
  1644. } catch(ex) {
  1645. }
  1646. if ( !lc ) {
  1647. return vAPI.noTabId;
  1648. }
  1649. }
  1650. if ( lc.topFrameElement ) {
  1651. return tabWatcher.tabIdFromTarget(lc.topFrameElement);
  1652. }
  1653. var win;
  1654. try {
  1655. win = lc.associatedWindow;
  1656. } catch (ex) { }
  1657. if ( !win ) {
  1658. return vAPI.noTabId;
  1659. }
  1660. if ( win.top ) {
  1661. win = win.top;
  1662. }
  1663. var tabBrowser;
  1664. try {
  1665. tabBrowser = getTabBrowser(
  1666. win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation)
  1667. .QueryInterface(Ci.nsIDocShell).rootTreeItem
  1668. .QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow)
  1669. );
  1670. } catch (ex) { }
  1671. if ( !tabBrowser ) {
  1672. return vAPI.noTabId;
  1673. }
  1674. if ( tabBrowser.getBrowserForContentWindow ) {
  1675. return tabWatcher.tabIdFromTarget(tabBrowser.getBrowserForContentWindow(win));
  1676. }
  1677. // Falling back onto _getTabForContentWindow to ensure older versions
  1678. // of Firefox work well.
  1679. return tabBrowser._getTabForContentWindow ?
  1680. tabWatcher.tabIdFromTarget(tabBrowser._getTabForContentWindow(win)) :
  1681. vAPI.noTabId;
  1682. },
  1683. rawtypeFromContentType: function(channel) {
  1684. var mime = channel.contentType;
  1685. if ( !mime ) {
  1686. return 0;
  1687. }
  1688. var pos = mime.indexOf('/');
  1689. if ( pos === -1 ) {
  1690. pos = mime.length;
  1691. }
  1692. return this.mimeTypeMap[mime.slice(0, pos)] || 0;
  1693. },
  1694. observe: function(channel, topic) {
  1695. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  1696. return;
  1697. }
  1698. var URI = channel.URI;
  1699. var channelData = this.channelDataFromChannel(channel);
  1700. if ( topic.lastIndexOf('http-on-examine-', 0) === 0 ) {
  1701. if ( channelData === null ) {
  1702. return;
  1703. }
  1704. var type = this.frameTypeMap[channelData[1]];
  1705. if ( !type ) {
  1706. return;
  1707. }
  1708. topic = 'Content-Security-Policy';
  1709. var result;
  1710. try {
  1711. result = channel.getResponseHeader(topic);
  1712. } catch (ex) {
  1713. result = null;
  1714. }
  1715. result = vAPI.net.onHeadersReceived.callback({
  1716. parentFrameId: type === 'main_frame' ? -1 : 0,
  1717. responseHeaders: result ? [{name: topic, value: result}] : [],
  1718. tabId: channelData[0],
  1719. type: type,
  1720. url: URI.asciiSpec
  1721. });
  1722. if ( result ) {
  1723. channel.setResponseHeader(
  1724. topic,
  1725. result.responseHeaders.pop().value,
  1726. true
  1727. );
  1728. }
  1729. return;
  1730. }
  1731. // http-on-modify-request
  1732. // The channel was previously serviced.
  1733. if ( channelData !== null ) {
  1734. this.handleRequest(channel, URI, channelData[0], channelData[1]);
  1735. return;
  1736. }
  1737. // The channel was never serviced.
  1738. var tabId;
  1739. var pendingRequest = this.lookupPendingRequest(URI.asciiSpec);
  1740. var rawType = 1;
  1741. var loadInfo = channel.loadInfo;
  1742. // https://github.com/gorhill/uMatrix/issues/390#issuecomment-155717004
  1743. if ( loadInfo ) {
  1744. rawType = loadInfo.externalContentPolicyType !== undefined ?
  1745. loadInfo.externalContentPolicyType :
  1746. loadInfo.contentPolicyType;
  1747. if ( !rawType ) {
  1748. rawType = 1;
  1749. }
  1750. }
  1751. if ( pendingRequest !== null ) {
  1752. tabId = pendingRequest.tabId;
  1753. // https://github.com/gorhill/uBlock/issues/654
  1754. // Use the request type from the HTTP observer point of view.
  1755. if ( rawType !== 1 ) {
  1756. pendingRequest.rawType = rawType;
  1757. } else {
  1758. rawType = pendingRequest.rawType;
  1759. }
  1760. } else {
  1761. tabId = this.tabIdFromChannel(channel);
  1762. }
  1763. if ( this.handleRequest(channel, URI, tabId, rawType) ) {
  1764. return;
  1765. }
  1766. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1767. return;
  1768. }
  1769. // Carry data for behind-the-scene redirects
  1770. channel.setProperty(this.REQDATAKEY, [tabId, rawType]);
  1771. },
  1772. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1773. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1774. // If error thrown, the redirect will fail
  1775. try {
  1776. var URI = newChannel.URI;
  1777. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1778. return;
  1779. }
  1780. if ( newChannel instanceof Ci.nsIWritablePropertyBag === false ) {
  1781. return;
  1782. }
  1783. var channelData = this.channelDataFromChannel(oldChannel);
  1784. if ( channelData === null ) {
  1785. return;
  1786. }
  1787. // Carry the data on in case of multiple redirects
  1788. newChannel.setProperty(this.REQDATAKEY, channelData);
  1789. } catch (ex) {
  1790. // console.error(ex);
  1791. } finally {
  1792. callback.onRedirectVerifyCallback(this.ACCEPT);
  1793. }
  1794. }
  1795. };
  1796. /******************************************************************************/
  1797. vAPI.net = {};
  1798. /******************************************************************************/
  1799. vAPI.net.registerListeners = function() {
  1800. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1801. new Set(this.onBeforeRequest.types) :
  1802. null;
  1803. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1804. new Set(this.onBeforeSendHeaders.types) :
  1805. null;
  1806. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  1807. var shouldLoadListener = function(e) {
  1808. var details = e.data;
  1809. var pendingReq = httpObserver.createPendingRequest(details.url);
  1810. pendingReq.rawType = details.rawType;
  1811. pendingReq.tabId = tabWatcher.tabIdFromTarget(e.target);
  1812. };
  1813. // https://github.com/gorhill/uMatrix/issues/200
  1814. // We need this only for Firefox 34 and less: the tab id is derived from
  1815. // the origin of the message.
  1816. if ( !vAPI.modernFirefox ) {
  1817. vAPI.messaging.globalMessageManager.addMessageListener(
  1818. shouldLoadListenerMessageName,
  1819. shouldLoadListener
  1820. );
  1821. }
  1822. httpObserver.register();
  1823. cleanupTasks.push(function() {
  1824. if ( !vAPI.modernFirefox ) {
  1825. vAPI.messaging.globalMessageManager.removeMessageListener(
  1826. shouldLoadListenerMessageName,
  1827. shouldLoadListener
  1828. );
  1829. }
  1830. httpObserver.unregister();
  1831. });
  1832. };
  1833. /******************************************************************************/
  1834. /******************************************************************************/
  1835. vAPI.toolbarButton = {
  1836. id: location.host + '-button',
  1837. type: 'view',
  1838. viewId: location.host + '-panel',
  1839. label: vAPI.app.name,
  1840. tooltiptext: vAPI.app.name,
  1841. tabs: {/*tabId: {badge: 0, img: boolean}*/},
  1842. init: null,
  1843. codePath: ''
  1844. };
  1845. /******************************************************************************/
  1846. // Non-Fennec: common code paths.
  1847. (function() {
  1848. if ( vAPI.fennec ) {
  1849. return;
  1850. }
  1851. var tbb = vAPI.toolbarButton;
  1852. var popupCommittedWidth = 0;
  1853. var popupCommittedHeight = 0;
  1854. tbb.onViewShowing = function({target}) {
  1855. popupCommittedWidth = popupCommittedHeight = 0;
  1856. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1857. };
  1858. tbb.onViewHiding = function({target}) {
  1859. target.parentNode.style.maxWidth = '';
  1860. target.firstChild.setAttribute('src', 'about:blank');
  1861. };
  1862. tbb.updateState = function(win, tabId) {
  1863. var button = win.document.getElementById(this.id);
  1864. if ( !button ) {
  1865. return;
  1866. }
  1867. var icon = this.tabs[tabId];
  1868. button.setAttribute('badge', icon && icon.badge || '');
  1869. button.classList.toggle('off', !icon || !icon.img);
  1870. var iconId = icon && icon.img ? icon.img : 'off';
  1871. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1872. button.style.listStyleImage = icon;
  1873. };
  1874. tbb.populatePanel = function(doc, panel) {
  1875. panel.setAttribute('id', this.viewId);
  1876. var iframe = doc.createElement('iframe');
  1877. iframe.setAttribute('type', 'content');
  1878. panel.appendChild(iframe);
  1879. var toPx = function(pixels) {
  1880. return pixels.toString() + 'px';
  1881. };
  1882. var scrollBarWidth = 0;
  1883. var resizeTimer = null;
  1884. var resizePopupDelayed = function(attempts) {
  1885. if ( resizeTimer !== null ) {
  1886. return false;
  1887. }
  1888. // Sanity check
  1889. attempts = (attempts || 0) + 1;
  1890. if ( attempts > 1/*000*/ ) {
  1891. //console.error('uMatrix> resizePopupDelayed: giving up after too many attempts');
  1892. return false;
  1893. }
  1894. resizeTimer = vAPI.setTimeout(resizePopup, 10, attempts);
  1895. return true;
  1896. };
  1897. var resizePopup = function(attempts) {
  1898. resizeTimer = null;
  1899. panel.parentNode.style.maxWidth = 'none';
  1900. var body = iframe.contentDocument.body;
  1901. // https://github.com/gorhill/uMatrix/issues/301
  1902. // Don't resize if committed size did not change.
  1903. if (
  1904. popupCommittedWidth === body.clientWidth &&
  1905. popupCommittedHeight === body.clientHeight
  1906. ) {
  1907. return;
  1908. }
  1909. // We set a limit for height
  1910. var height = Math.min(body.clientHeight, 600);
  1911. // https://github.com/chrisaljoudi/uBlock/issues/730
  1912. // Voodoo programming: this recipe works
  1913. panel.style.setProperty('height', toPx(height));
  1914. iframe.style.setProperty('height', toPx(height));
  1915. // Adjust width for presence/absence of vertical scroll bar which may
  1916. // have appeared as a result of last operation.
  1917. var contentWindow = iframe.contentWindow;
  1918. var width = body.clientWidth;
  1919. if ( contentWindow.scrollMaxY !== 0 ) {
  1920. width += scrollBarWidth;
  1921. }
  1922. panel.style.setProperty('width', toPx(width));
  1923. // scrollMaxX should always be zero once we know the scrollbar width
  1924. if ( contentWindow.scrollMaxX !== 0 ) {
  1925. scrollBarWidth = contentWindow.scrollMaxX;
  1926. width += scrollBarWidth;
  1927. panel.style.setProperty('width', toPx(width));
  1928. }
  1929. if ( iframe.clientHeight !== height || panel.clientWidth !== width ) {
  1930. if ( resizePopupDelayed(attempts) ) {
  1931. return;
  1932. }
  1933. // resizePopupDelayed won't be called again, so commit
  1934. // dimentsions.
  1935. }
  1936. popupCommittedWidth = body.clientWidth;
  1937. popupCommittedHeight = body.clientHeight;
  1938. };
  1939. var onResizeRequested = function() {
  1940. var body = iframe.contentDocument.body;
  1941. if ( body.getAttribute('data-resize-popup') !== 'true' ) {
  1942. return;
  1943. }
  1944. body.removeAttribute('data-resize-popup');
  1945. resizePopupDelayed();
  1946. };
  1947. var onPopupReady = function() {
  1948. var win = this.contentWindow;
  1949. if ( !win || win.location.host !== location.host ) {
  1950. return;
  1951. }
  1952. if ( typeof tbb.onBeforePopupReady === 'function' ) {
  1953. tbb.onBeforePopupReady.call(this);
  1954. }
  1955. resizePopupDelayed();
  1956. var body = win.document.body;
  1957. body.removeAttribute('data-resize-popup');
  1958. var mutationObserver = new win.MutationObserver(onResizeRequested);
  1959. mutationObserver.observe(body, {
  1960. attributes: true,
  1961. attributeFilter: [ 'data-resize-popup' ]
  1962. });
  1963. };
  1964. iframe.addEventListener('load', onPopupReady, true);
  1965. };
  1966. })();
  1967. /******************************************************************************/
  1968. // Firefox 28 and less
  1969. (function() {
  1970. var tbb = vAPI.toolbarButton;
  1971. if ( tbb.init !== null ) {
  1972. return;
  1973. }
  1974. var CustomizableUI = null;
  1975. var forceLegacyToolbarButton = vAPI.localStorage.getBool('forceLegacyToolbarButton');
  1976. if ( !forceLegacyToolbarButton ) {
  1977. try {
  1978. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1979. } catch (ex) {
  1980. }
  1981. }
  1982. if ( CustomizableUI !== null ) {
  1983. return;
  1984. }
  1985. tbb.codePath = 'legacy';
  1986. tbb.id = 'umatrix-legacy-button'; // NOTE: must match legacy-toolbar-button.css
  1987. tbb.viewId = tbb.id + '-panel';
  1988. var styleSheetUri = null;
  1989. var createToolbarButton = function(window) {
  1990. var document = window.document;
  1991. var toolbarButton = document.createElement('toolbarbutton');
  1992. toolbarButton.setAttribute('id', tbb.id);
  1993. // type = panel would be more accurate, but doesn't look as good
  1994. toolbarButton.setAttribute('type', 'menu');
  1995. toolbarButton.setAttribute('removable', 'true');
  1996. toolbarButton.setAttribute('class', 'toolbarbutton-1 chromeclass-toolbar-additional');
  1997. toolbarButton.setAttribute('label', tbb.label);
  1998. toolbarButton.setAttribute('tooltiptext', tbb.label);
  1999. var toolbarButtonPanel = document.createElement('panel');
  2000. // NOTE: Setting level to parent breaks the popup for PaleMoon under
  2001. // linux (mouse pointer misaligned with content). For some reason.
  2002. // toolbarButtonPanel.setAttribute('level', 'parent');
  2003. tbb.populatePanel(document, toolbarButtonPanel);
  2004. toolbarButtonPanel.addEventListener('popupshowing', tbb.onViewShowing);
  2005. toolbarButtonPanel.addEventListener('popuphiding', tbb.onViewHiding);
  2006. toolbarButton.appendChild(toolbarButtonPanel);
  2007. return toolbarButton;
  2008. };
  2009. var addLegacyToolbarButton = function(window) {
  2010. // uMatrix's stylesheet lazily added.
  2011. if ( styleSheetUri === null ) {
  2012. var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
  2013. .getService(Ci.nsIStyleSheetService);
  2014. styleSheetUri = Services.io.newURI(vAPI.getURL("css/legacy-toolbar-button.css"), null, null);
  2015. // Register global so it works in all windows, including palette
  2016. if ( !sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  2017. sss.loadAndRegisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  2018. }
  2019. }
  2020. var document = window.document;
  2021. // https://github.com/gorhill/uMatrix/issues/357
  2022. // Already installed?
  2023. if ( document.getElementById(tbb.id) !== null ) {
  2024. return;
  2025. }
  2026. var toolbox = document.getElementById('navigator-toolbox') ||
  2027. document.getElementById('mail-toolbox');
  2028. if ( toolbox === null ) {
  2029. return;
  2030. }
  2031. var toolbarButton = createToolbarButton(window);
  2032. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/toolbarpalette
  2033. var palette = toolbox.palette;
  2034. if ( palette && palette.querySelector('#' + tbb.id) === null ) {
  2035. palette.appendChild(toolbarButton);
  2036. }
  2037. // Find the place to put the button.
  2038. // Pale Moon: `toolbox.externalToolbars` can be undefined. Seen while
  2039. // testing popup test number 3:
  2040. // http://raymondhill.net/ublock/popup.html
  2041. var toolbars = toolbox.externalToolbars ? toolbox.externalToolbars.slice() : [];
  2042. for ( var child of toolbox.children ) {
  2043. if ( child.localName === 'toolbar' ) {
  2044. toolbars.push(child);
  2045. }
  2046. }
  2047. for ( var toolbar of toolbars ) {
  2048. var currentsetString = toolbar.getAttribute('currentset');
  2049. if ( !currentsetString ) {
  2050. continue;
  2051. }
  2052. var currentset = currentsetString.split(/\s*,\s*/);
  2053. var index = currentset.indexOf(tbb.id);
  2054. if ( index === -1 ) {
  2055. continue;
  2056. }
  2057. // This can occur with Pale Moon:
  2058. // "TypeError: toolbar.insertItem is not a function"
  2059. if ( typeof toolbar.insertItem !== 'function' ) {
  2060. continue;
  2061. }
  2062. // Found our button on this toolbar - but where on it?
  2063. var before = null;
  2064. for ( var i = index + 1; i < currentset.length; i++ ) {
  2065. before = toolbar.querySelector('[id="' + currentset[i] + '"]');
  2066. if ( before !== null ) {
  2067. break;
  2068. }
  2069. }
  2070. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Method/insertItem
  2071. toolbar.insertItem(tbb.id, before);
  2072. break;
  2073. }
  2074. // https://github.com/gorhill/uBlock/issues/763
  2075. // We are done if our toolbar button is already installed in one of the
  2076. // toolbar.
  2077. if ( palette !== null && toolbarButton.parentElement !== palette ) {
  2078. return;
  2079. }
  2080. // No button yet so give it a default location. If forcing the button,
  2081. // just put in in the palette rather than on any specific toolbar (who
  2082. // knows what toolbars will be available or visible!)
  2083. var navbar = document.getElementById('nav-bar');
  2084. if ( navbar !== null && !vAPI.localStorage.getBool('legacyToolbarButtonAdded') ) {
  2085. // https://github.com/gorhill/uBlock/issues/264
  2086. // Find a child customizable palette, if any.
  2087. navbar = navbar.querySelector('.customization-target') || navbar;
  2088. navbar.appendChild(toolbarButton);
  2089. navbar.setAttribute('currentset', navbar.currentSet);
  2090. document.persist(navbar.id, 'currentset');
  2091. vAPI.localStorage.setBool('legacyToolbarButtonAdded', 'true');
  2092. }
  2093. };
  2094. var canAddLegacyToolbarButton = function(window) {
  2095. var document = window.document;
  2096. if (
  2097. !document ||
  2098. document.readyState !== 'complete' ||
  2099. document.getElementById('nav-bar') === null
  2100. ) {
  2101. return false;
  2102. }
  2103. var toolbox = document.getElementById('navigator-toolbox') ||
  2104. document.getElementById('mail-toolbox');
  2105. return toolbox !== null && !!toolbox.palette;
  2106. };
  2107. var onPopupCloseRequested = function({target}) {
  2108. var document = target.ownerDocument;
  2109. if ( !document ) {
  2110. return;
  2111. }
  2112. var toolbarButtonPanel = document.getElementById(tbb.viewId);
  2113. if ( toolbarButtonPanel === null ) {
  2114. return;
  2115. }
  2116. // `hidePopup` reported as not existing while testing legacy button
  2117. // on FF 41.0.2.
  2118. // https://bugzilla.mozilla.org/show_bug.cgi?id=1151796
  2119. if ( typeof toolbarButtonPanel.hidePopup === 'function' ) {
  2120. toolbarButtonPanel.hidePopup();
  2121. }
  2122. };
  2123. var shutdown = function() {
  2124. for ( var win of winWatcher.getWindows() ) {
  2125. var toolbarButton = win.document.getElementById(tbb.id);
  2126. if ( toolbarButton ) {
  2127. toolbarButton.parentNode.removeChild(toolbarButton);
  2128. }
  2129. }
  2130. if ( styleSheetUri !== null ) {
  2131. var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
  2132. .getService(Ci.nsIStyleSheetService);
  2133. if ( sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  2134. sss.unregisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  2135. }
  2136. styleSheetUri = null;
  2137. }
  2138. vAPI.messaging.globalMessageManager.removeMessageListener(
  2139. location.host + ':closePopup',
  2140. onPopupCloseRequested
  2141. );
  2142. };
  2143. tbb.attachToNewWindow = function(win) {
  2144. deferUntil(
  2145. canAddLegacyToolbarButton.bind(null, win),
  2146. addLegacyToolbarButton.bind(null, win)
  2147. );
  2148. };
  2149. tbb.init = function() {
  2150. vAPI.messaging.globalMessageManager.addMessageListener(
  2151. location.host + ':closePopup',
  2152. onPopupCloseRequested
  2153. );
  2154. cleanupTasks.push(shutdown);
  2155. };
  2156. })();
  2157. /******************************************************************************/
  2158. // Firefox Australis < 36.
  2159. (function() {
  2160. var tbb = vAPI.toolbarButton;
  2161. if ( tbb.init !== null ) {
  2162. return;
  2163. }
  2164. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') >= 0 ) {
  2165. return null;
  2166. }
  2167. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  2168. return null;
  2169. }
  2170. var CustomizableUI = null;
  2171. try {
  2172. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  2173. } catch (ex) {
  2174. }
  2175. if ( CustomizableUI === null ) {
  2176. return;
  2177. }
  2178. tbb.codePath = 'australis';
  2179. tbb.CustomizableUI = CustomizableUI;
  2180. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  2181. var styleURI = null;
  2182. var onPopupCloseRequested = function({target}) {
  2183. if ( typeof tbb.closePopup === 'function' ) {
  2184. tbb.closePopup(target);
  2185. }
  2186. };
  2187. var shutdown = function() {
  2188. CustomizableUI.destroyWidget(tbb.id);
  2189. for ( var win of winWatcher.getWindows() ) {
  2190. var panel = win.document.getElementById(tbb.viewId);
  2191. panel.parentNode.removeChild(panel);
  2192. win.QueryInterface(Ci.nsIInterfaceRequestor)
  2193. .getInterface(Ci.nsIDOMWindowUtils)
  2194. .removeSheet(styleURI, 1);
  2195. }
  2196. vAPI.messaging.globalMessageManager.removeMessageListener(
  2197. location.host + ':closePopup',
  2198. onPopupCloseRequested
  2199. );
  2200. };
  2201. tbb.onBeforeCreated = function(doc) {
  2202. var panel = doc.createElement('panelview');
  2203. this.populatePanel(doc, panel);
  2204. doc.getElementById('PanelUI-multiView').appendChild(panel);
  2205. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  2206. .getInterface(Ci.nsIDOMWindowUtils)
  2207. .loadSheet(styleURI, 1);
  2208. };
  2209. tbb.onBeforePopupReady = function() {
  2210. // https://github.com/gorhill/uBlock/issues/83
  2211. // Add `portrait` class if width is constrained.
  2212. try {
  2213. this.contentDocument.body.classList.toggle(
  2214. 'portrait',
  2215. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  2216. );
  2217. } catch (ex) {
  2218. /* noop */
  2219. }
  2220. };
  2221. tbb.init = function() {
  2222. vAPI.messaging.globalMessageManager.addMessageListener(
  2223. location.host + ':closePopup',
  2224. onPopupCloseRequested
  2225. );
  2226. var style = [
  2227. '#' + this.id + '.off {',
  2228. 'list-style-image: url(',
  2229. vAPI.getURL('img/browsericons/icon19-off.png'),
  2230. ');',
  2231. '}',
  2232. '#' + this.id + ' {',
  2233. 'list-style-image: url(',
  2234. vAPI.getURL('img/browsericons/icon19.png'),
  2235. ');',
  2236. '}',
  2237. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  2238. 'width: 160px;',
  2239. 'height: 290px;',
  2240. 'overflow: hidden !important;',
  2241. '}',
  2242. '#' + this.id + '[badge]:not([badge=""])::after {',
  2243. 'position: absolute;',
  2244. 'margin-left: -16px;',
  2245. 'margin-top: 3px;',
  2246. 'padding: 1px 2px;',
  2247. 'font-size: 9px;',
  2248. 'font-weight: bold;',
  2249. 'color: #fff;',
  2250. 'background: #000;',
  2251. 'content: attr(badge);',
  2252. '}'
  2253. ];
  2254. styleURI = Services.io.newURI(
  2255. 'data:text/css,' + encodeURIComponent(style.join('')),
  2256. null,
  2257. null
  2258. );
  2259. this.closePopup = function(tabBrowser) {
  2260. CustomizableUI.hidePanelForNode(
  2261. tabBrowser.ownerDocument.getElementById(this.viewId)
  2262. );
  2263. };
  2264. CustomizableUI.createWidget(this);
  2265. cleanupTasks.push(shutdown);
  2266. };
  2267. })();
  2268. /******************************************************************************/
  2269. // Firefox Australis >= 36.
  2270. (function() {
  2271. var tbb = vAPI.toolbarButton;
  2272. if ( tbb.init !== null ) {
  2273. return;
  2274. }
  2275. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') < 0 ) {
  2276. return null;
  2277. }
  2278. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  2279. return null;
  2280. }
  2281. var CustomizableUI = null;
  2282. try {
  2283. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  2284. } catch (ex) {
  2285. }
  2286. if ( CustomizableUI === null ) {
  2287. return null;
  2288. }
  2289. tbb.codePath = 'australis';
  2290. tbb.CustomizableUI = CustomizableUI;
  2291. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  2292. var CUIEvents = {};
  2293. var badgeCSSRules = [
  2294. 'background: #000',
  2295. 'color: #fff'
  2296. ].join(';');
  2297. var updateBadgeStyle = function() {
  2298. for ( var win of winWatcher.getWindows() ) {
  2299. var button = win.document.getElementById(tbb.id);
  2300. if ( button === null ) {
  2301. continue;
  2302. }
  2303. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  2304. button,
  2305. 'class',
  2306. 'toolbarbutton-badge'
  2307. );
  2308. if ( !badge ) {
  2309. continue;
  2310. }
  2311. badge.style.cssText = badgeCSSRules;
  2312. }
  2313. };
  2314. var updateBadge = function() {
  2315. var wId = tbb.id;
  2316. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  2317. for ( var win of winWatcher.getWindows() ) {
  2318. var button = win.document.getElementById(wId);
  2319. if ( button === null ) {
  2320. continue;
  2321. }
  2322. if ( buttonInPanel ) {
  2323. button.classList.remove('badged-button');
  2324. continue;
  2325. }
  2326. button.classList.add('badged-button');
  2327. }
  2328. if ( buttonInPanel ) {
  2329. return;
  2330. }
  2331. // Anonymous elements need some time to be reachable
  2332. vAPI.setTimeout(updateBadgeStyle, 250);
  2333. }.bind(CUIEvents);
  2334. // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/CustomizableUI.jsm#Listeners
  2335. CUIEvents.onCustomizeEnd = updateBadge;
  2336. CUIEvents.onWidgetAdded = updateBadge;
  2337. CUIEvents.onWidgetUnderflow = updateBadge;
  2338. var onPopupCloseRequested = function({target}) {
  2339. if ( typeof tbb.closePopup === 'function' ) {
  2340. tbb.closePopup(target);
  2341. }
  2342. };
  2343. var shutdown = function() {
  2344. for ( var win of winWatcher.getWindows() ) {
  2345. var panel = win.document.getElementById(tbb.viewId);
  2346. if ( panel !== null && panel.parentNode !== null ) {
  2347. panel.parentNode.removeChild(panel);
  2348. }
  2349. win.QueryInterface(Ci.nsIInterfaceRequestor)
  2350. .getInterface(Ci.nsIDOMWindowUtils)
  2351. .removeSheet(styleURI, 1);
  2352. }
  2353. CustomizableUI.removeListener(CUIEvents);
  2354. CustomizableUI.destroyWidget(tbb.id);
  2355. vAPI.messaging.globalMessageManager.removeMessageListener(
  2356. location.host + ':closePopup',
  2357. onPopupCloseRequested
  2358. );
  2359. };
  2360. var styleURI = null;
  2361. tbb.onBeforeCreated = function(doc) {
  2362. var panel = doc.createElement('panelview');
  2363. this.populatePanel(doc, panel);
  2364. doc.getElementById('PanelUI-multiView').appendChild(panel);
  2365. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  2366. .getInterface(Ci.nsIDOMWindowUtils)
  2367. .loadSheet(styleURI, 1);
  2368. };
  2369. tbb.onCreated = function(button) {
  2370. button.setAttribute('badge', '');
  2371. vAPI.setTimeout(updateBadge, 250);
  2372. };
  2373. tbb.onBeforePopupReady = function() {
  2374. // https://github.com/gorhill/uBlock/issues/83
  2375. // Add `portrait` class if width is constrained.
  2376. try {
  2377. this.contentDocument.body.classList.toggle(
  2378. 'portrait',
  2379. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  2380. );
  2381. } catch (ex) {
  2382. /* noop */
  2383. }
  2384. };
  2385. tbb.closePopup = function(tabBrowser) {
  2386. CustomizableUI.hidePanelForNode(
  2387. tabBrowser.ownerDocument.getElementById(tbb.viewId)
  2388. );
  2389. };
  2390. tbb.init = function() {
  2391. vAPI.messaging.globalMessageManager.addMessageListener(
  2392. location.host + ':closePopup',
  2393. onPopupCloseRequested
  2394. );
  2395. CustomizableUI.addListener(CUIEvents);
  2396. var style = [
  2397. '#' + this.id + '.off {',
  2398. 'list-style-image: url(',
  2399. vAPI.getURL('img/browsericons/icon19-off.png'),
  2400. ');',
  2401. '}',
  2402. '#' + this.id + ' {',
  2403. 'list-style-image: url(',
  2404. vAPI.getURL('img/browsericons/icon19-19.png'),
  2405. ');',
  2406. '}',
  2407. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  2408. 'width: 160px;',
  2409. 'height: 290px;',
  2410. 'overflow: hidden !important;',
  2411. '}'
  2412. ];
  2413. styleURI = Services.io.newURI(
  2414. 'data:text/css,' + encodeURIComponent(style.join('')),
  2415. null,
  2416. null
  2417. );
  2418. CustomizableUI.createWidget(this);
  2419. cleanupTasks.push(shutdown);
  2420. };
  2421. })();
  2422. /******************************************************************************/
  2423. // No toolbar button.
  2424. (function() {
  2425. // Just to ensure the number of cleanup tasks is as expected: toolbar
  2426. // button code is one single cleanup task regardless of platform.
  2427. if ( vAPI.toolbarButton.init === null ) {
  2428. cleanupTasks.push(function(){});
  2429. }
  2430. })();
  2431. /******************************************************************************/
  2432. if ( vAPI.toolbarButton.init !== null ) {
  2433. vAPI.toolbarButton.init();
  2434. }
  2435. /******************************************************************************/
  2436. /******************************************************************************/
  2437. vAPI.contextMenu = {
  2438. contextMap: {
  2439. frame: 'inFrame',
  2440. link: 'onLink',
  2441. image: 'onImage',
  2442. audio: 'onAudio',
  2443. video: 'onVideo',
  2444. editable: 'onEditableArea'
  2445. }
  2446. };
  2447. /******************************************************************************/
  2448. vAPI.contextMenu.displayMenuItem = function({target}) {
  2449. var doc = target.ownerDocument;
  2450. var gContextMenu = doc.defaultView.gContextMenu;
  2451. if ( !gContextMenu.browser ) {
  2452. return;
  2453. }
  2454. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  2455. var currentURI = gContextMenu.browser.currentURI;
  2456. // https://github.com/chrisaljoudi/uBlock/issues/105
  2457. // TODO: Should the element picker works on any kind of pages?
  2458. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  2459. menuitem.setAttribute('hidden', true);
  2460. return;
  2461. }
  2462. var ctx = vAPI.contextMenu.contexts;
  2463. if ( !ctx ) {
  2464. menuitem.setAttribute('hidden', false);
  2465. return;
  2466. }
  2467. var ctxMap = vAPI.contextMenu.contextMap;
  2468. for ( var context of ctx ) {
  2469. if (
  2470. context === 'page' &&
  2471. !gContextMenu.onLink &&
  2472. !gContextMenu.onImage &&
  2473. !gContextMenu.onEditableArea &&
  2474. !gContextMenu.inFrame &&
  2475. !gContextMenu.onVideo &&
  2476. !gContextMenu.onAudio
  2477. ) {
  2478. menuitem.setAttribute('hidden', false);
  2479. return;
  2480. }
  2481. if (
  2482. ctxMap.hasOwnProperty(context) &&
  2483. gContextMenu[ctxMap[context]]
  2484. ) {
  2485. menuitem.setAttribute('hidden', false);
  2486. return;
  2487. }
  2488. }
  2489. menuitem.setAttribute('hidden', true);
  2490. };
  2491. /******************************************************************************/
  2492. vAPI.contextMenu.register = (function() {
  2493. var register = function(doc) {
  2494. if ( !this.menuItemId ) {
  2495. return;
  2496. }
  2497. // Already installed?
  2498. if ( doc.getElementById(this.menuItemId) !== null ) {
  2499. return;
  2500. }
  2501. var contextMenu = doc.getElementById('contentAreaContextMenu');
  2502. var menuitem = doc.createElement('menuitem');
  2503. menuitem.setAttribute('id', this.menuItemId);
  2504. menuitem.setAttribute('label', this.menuLabel);
  2505. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  2506. menuitem.setAttribute('class', 'menuitem-iconic');
  2507. menuitem.addEventListener('command', this.onCommand);
  2508. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  2509. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  2510. };
  2511. // https://github.com/gorhill/uBlock/issues/906
  2512. // Be sure document.readyState is 'complete': it could happen at launch
  2513. // time that we are called by vAPI.contextMenu.create() directly before
  2514. // the environment is properly initialized.
  2515. var registerSafely = function(doc, tryCount) {
  2516. if ( doc.readyState === 'complete' ) {
  2517. register.call(this, doc);
  2518. return;
  2519. }
  2520. if ( typeof tryCount !== 'number' ) {
  2521. tryCount = 0;
  2522. }
  2523. tryCount += 1;
  2524. if ( tryCount < 8 ) {
  2525. vAPI.setTimeout(registerSafely.bind(this, doc, tryCount), 200);
  2526. }
  2527. };
  2528. return registerSafely;
  2529. })();
  2530. /******************************************************************************/
  2531. vAPI.contextMenu.unregister = function(doc) {
  2532. if ( !this.menuItemId ) {
  2533. return;
  2534. }
  2535. var menuitem = doc.getElementById(this.menuItemId);
  2536. if ( menuitem === null ) {
  2537. return;
  2538. }
  2539. var contextMenu = menuitem.parentNode;
  2540. menuitem.removeEventListener('command', this.onCommand);
  2541. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  2542. contextMenu.removeChild(menuitem);
  2543. };
  2544. /******************************************************************************/
  2545. vAPI.contextMenu.create = function(details, callback) {
  2546. this.menuItemId = details.id;
  2547. this.menuLabel = details.title;
  2548. this.contexts = details.contexts;
  2549. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  2550. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  2551. } else {
  2552. // default in Chrome
  2553. this.contexts = ['page'];
  2554. }
  2555. this.onCommand = function() {
  2556. var gContextMenu = getOwnerWindow(this).gContextMenu;
  2557. var details = {
  2558. menuItemId: this.id
  2559. };
  2560. if ( gContextMenu.inFrame ) {
  2561. details.tagName = 'iframe';
  2562. // Probably won't work with e10s
  2563. details.frameUrl = gContextMenu.focusedWindow.location.href;
  2564. } else if ( gContextMenu.onImage ) {
  2565. details.tagName = 'img';
  2566. details.srcUrl = gContextMenu.mediaURL;
  2567. } else if ( gContextMenu.onAudio ) {
  2568. details.tagName = 'audio';
  2569. details.srcUrl = gContextMenu.mediaURL;
  2570. } else if ( gContextMenu.onVideo ) {
  2571. details.tagName = 'video';
  2572. details.srcUrl = gContextMenu.mediaURL;
  2573. } else if ( gContextMenu.onLink ) {
  2574. details.tagName = 'a';
  2575. details.linkUrl = gContextMenu.linkURL;
  2576. }
  2577. callback(details, {
  2578. id: tabWatcher.tabIdFromTarget(gContextMenu.browser),
  2579. url: gContextMenu.browser.currentURI.asciiSpec
  2580. });
  2581. };
  2582. for ( var win of winWatcher.getWindows() ) {
  2583. this.register(win.document);
  2584. }
  2585. };
  2586. /******************************************************************************/
  2587. vAPI.contextMenu.remove = function() {
  2588. for ( var win of winWatcher.getWindows() ) {
  2589. this.unregister(win.document);
  2590. }
  2591. this.menuItemId = null;
  2592. this.menuLabel = null;
  2593. this.contexts = null;
  2594. this.onCommand = null;
  2595. };
  2596. /******************************************************************************/
  2597. /******************************************************************************/
  2598. var optionsObserver = (function() {
  2599. var addonId = 'uMatrix@raymondhill.net';
  2600. var commandHandler = function() {
  2601. switch ( this.id ) {
  2602. case 'showDashboardButton':
  2603. vAPI.tabs.open({ url: 'dashboard.html', index: -1 });
  2604. break;
  2605. case 'showLoggerButton':
  2606. vAPI.tabs.open({ url: 'logger-ui.html', index: -1 });
  2607. break;
  2608. default:
  2609. break;
  2610. }
  2611. };
  2612. var setupOptionsButton = function(doc, id) {
  2613. var button = doc.getElementById(id);
  2614. if ( button === null ) {
  2615. return;
  2616. }
  2617. button.addEventListener('command', commandHandler);
  2618. button.label = vAPI.i18n(id);
  2619. };
  2620. var setupOptionsButtons = function(doc) {
  2621. setupOptionsButton(doc, 'showDashboardButton');
  2622. setupOptionsButton(doc, 'showLoggerButton');
  2623. };
  2624. var observer = {
  2625. observe: function(doc, topic, id) {
  2626. if ( id !== addonId ) {
  2627. return;
  2628. }
  2629. setupOptionsButtons(doc);
  2630. }
  2631. };
  2632. // https://github.com/gorhill/uBlock/issues/948
  2633. // Older versions of Firefox can throw here when looking up `currentURI`.
  2634. var canInit = function() {
  2635. try {
  2636. var tabBrowser = tabWatcher.currentBrowser();
  2637. return tabBrowser &&
  2638. tabBrowser.currentURI &&
  2639. tabBrowser.currentURI.spec === 'about:addons' &&
  2640. tabBrowser.contentDocument &&
  2641. tabBrowser.contentDocument.readyState === 'complete';
  2642. } catch (ex) {
  2643. }
  2644. };
  2645. // Manually add the buttons if the `about:addons` page is already opened.
  2646. var init = function() {
  2647. if ( canInit() ) {
  2648. setupOptionsButtons(tabWatcher.currentBrowser().contentDocument);
  2649. }
  2650. };
  2651. var unregister = function() {
  2652. Services.obs.removeObserver(observer, 'addon-options-displayed');
  2653. };
  2654. var register = function() {
  2655. Services.obs.addObserver(observer, 'addon-options-displayed', false);
  2656. cleanupTasks.push(unregister);
  2657. deferUntil(canInit, init, { next: 463 });
  2658. };
  2659. return {
  2660. register: register,
  2661. unregister: unregister
  2662. };
  2663. })();
  2664. optionsObserver.register();
  2665. /******************************************************************************/
  2666. /******************************************************************************/
  2667. vAPI.lastError = function() {
  2668. return null;
  2669. };
  2670. /******************************************************************************/
  2671. /******************************************************************************/
  2672. // This is called only once, when everything has been loaded in memory after
  2673. // the extension was launched. It can be used to inject content scripts
  2674. // in already opened web pages, to remove whatever nuisance could make it to
  2675. // the web pages before uBlock was ready.
  2676. vAPI.onLoadAllCompleted = function() {
  2677. for ( var browser of tabWatcher.browsers() ) {
  2678. browser.messageManager.sendAsyncMessage(
  2679. location.host + '-load-completed'
  2680. );
  2681. }
  2682. };
  2683. /******************************************************************************/
  2684. /******************************************************************************/
  2685. // Likelihood is that we do not have to punycode: given punycode overhead,
  2686. // it's faster to check and skip than do it unconditionally all the time.
  2687. var punycodeHostname = punycode.toASCII;
  2688. var isNotASCII = /[^\x21-\x7F]/;
  2689. vAPI.punycodeHostname = function(hostname) {
  2690. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  2691. };
  2692. vAPI.punycodeURL = function(url) {
  2693. if ( isNotASCII.test(url) ) {
  2694. return Services.io.newURI(url, null, null).asciiSpec;
  2695. }
  2696. return url;
  2697. };
  2698. /******************************************************************************/
  2699. /******************************************************************************/
  2700. vAPI.cloud = (function() {
  2701. var extensionBranchPath = 'extensions.' + location.host;
  2702. var cloudBranchPath = extensionBranchPath + '.cloudStorage';
  2703. // https://github.com/gorhill/uBlock/issues/80#issuecomment-132081658
  2704. // We must use get/setComplexValue in order to properly handle strings
  2705. // with unicode characters.
  2706. var iss = Ci.nsISupportsString;
  2707. var argstr = Components.classes['@mozilla.org/supports-string;1']
  2708. .createInstance(iss);
  2709. var options = {
  2710. defaultDeviceName: '',
  2711. deviceName: ''
  2712. };
  2713. // User-supplied device name.
  2714. try {
  2715. options.deviceName = Services.prefs
  2716. .getBranch(extensionBranchPath + '.')
  2717. .getComplexValue('deviceName', iss)
  2718. .data;
  2719. } catch(ex) {
  2720. }
  2721. var getDefaultDeviceName = function() {
  2722. var name = '';
  2723. try {
  2724. name = Services.prefs
  2725. .getBranch('services.sync.client.')
  2726. .getComplexValue('name', iss)
  2727. .data;
  2728. } catch(ex) {
  2729. }
  2730. return name || window.navigator.platform || window.navigator.oscpu;
  2731. };
  2732. var start = function(dataKeys) {
  2733. var extensionBranch = Services.prefs.getBranch(extensionBranchPath + '.');
  2734. var syncBranch = Services.prefs.getBranch('services.sync.prefs.sync.');
  2735. // Mark config entries as syncable
  2736. argstr.data = '';
  2737. var dataKey;
  2738. for ( var i = 0; i < dataKeys.length; i++ ) {
  2739. dataKey = dataKeys[i];
  2740. if ( extensionBranch.prefHasUserValue('cloudStorage.' + dataKey) === false ) {
  2741. extensionBranch.setComplexValue('cloudStorage.' + dataKey, iss, argstr);
  2742. }
  2743. syncBranch.setBoolPref(cloudBranchPath + '.' + dataKey, true);
  2744. }
  2745. };
  2746. var push = function(datakey, data, callback) {
  2747. var branch = Services.prefs.getBranch(cloudBranchPath + '.');
  2748. var bin = {
  2749. 'source': options.deviceName || getDefaultDeviceName(),
  2750. 'tstamp': Date.now(),
  2751. 'data': data,
  2752. 'size': 0
  2753. };
  2754. bin.size = JSON.stringify(bin).length;
  2755. argstr.data = JSON.stringify(bin);
  2756. branch.setComplexValue(datakey, iss, argstr);
  2757. if ( typeof callback === 'function' ) {
  2758. callback();
  2759. }
  2760. };
  2761. var pull = function(datakey, callback) {
  2762. var result = null;
  2763. var branch = Services.prefs.getBranch(cloudBranchPath + '.');
  2764. try {
  2765. var json = branch.getComplexValue(datakey, iss).data;
  2766. if ( typeof json === 'string' ) {
  2767. result = JSON.parse(json);
  2768. }
  2769. } catch(ex) {
  2770. }
  2771. callback(result);
  2772. };
  2773. var getOptions = function(callback) {
  2774. if ( typeof callback !== 'function' ) {
  2775. return;
  2776. }
  2777. options.defaultDeviceName = getDefaultDeviceName();
  2778. callback(options);
  2779. };
  2780. var setOptions = function(details, callback) {
  2781. if ( typeof details !== 'object' || details === null ) {
  2782. return;
  2783. }
  2784. var branch = Services.prefs.getBranch(extensionBranchPath + '.');
  2785. if ( typeof details.deviceName === 'string' ) {
  2786. argstr.data = details.deviceName;
  2787. branch.setComplexValue('deviceName', iss, argstr);
  2788. options.deviceName = details.deviceName;
  2789. }
  2790. getOptions(callback);
  2791. };
  2792. return {
  2793. start: start,
  2794. push: push,
  2795. pull: pull,
  2796. getOptions: getOptions,
  2797. setOptions: setOptions
  2798. };
  2799. })();
  2800. /******************************************************************************/
  2801. /******************************************************************************/
  2802. vAPI.browserData = {};
  2803. /******************************************************************************/
  2804. // https://developer.mozilla.org/en-US/docs/HTTP_Cache
  2805. vAPI.browserData.clearCache = function(callback) {
  2806. // PURGE_DISK_DATA_ONLY:1
  2807. // PURGE_DISK_ALL:2
  2808. // PURGE_EVERYTHING:3
  2809. // However I verified that no argument does clear the cache data.
  2810. // There is no cache2 for older versions of Firefox.
  2811. if ( Services.cache2 ) {
  2812. Services.cache2.clear();
  2813. } else if ( Services.cache ) {
  2814. Services.cache.evictEntries(Services.cache.STORE_ON_DISK);
  2815. }
  2816. if ( typeof callback === 'function' ) {
  2817. callback();
  2818. }
  2819. };
  2820. /******************************************************************************/
  2821. vAPI.browserData.clearOrigin = function(/* domain */) {
  2822. // TODO
  2823. };
  2824. /******************************************************************************/
  2825. /******************************************************************************/
  2826. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager2
  2827. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  2828. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  2829. vAPI.cookies = {};
  2830. /******************************************************************************/
  2831. vAPI.cookies.CookieEntry = function(ffCookie) {
  2832. this.domain = ffCookie.host;
  2833. this.name = ffCookie.name;
  2834. this.path = ffCookie.path;
  2835. this.secure = ffCookie.isSecure === true;
  2836. this.session = ffCookie.expires === 0;
  2837. this.value = ffCookie.value;
  2838. };
  2839. /******************************************************************************/
  2840. vAPI.cookies.start = function() {
  2841. Services.obs.addObserver(this, 'cookie-changed', false);
  2842. Services.obs.addObserver(this, 'private-cookie-changed', false);
  2843. cleanupTasks.push(this.stop.bind(this));
  2844. };
  2845. /******************************************************************************/
  2846. vAPI.cookies.stop = function() {
  2847. Services.obs.removeObserver(this, 'cookie-changed');
  2848. Services.obs.removeObserver(this, 'private-cookie-changed');
  2849. };
  2850. /******************************************************************************/
  2851. vAPI.cookies.observe = function(subject, topic, reason) {
  2852. //if ( topic !== 'cookie-changed' && topic !== 'private-cookie-changed' ) {
  2853. // return;
  2854. //}
  2855. //
  2856. if ( reason === 'cleared' && typeof this.onAllRemoved === 'function' ) {
  2857. this.onAllRemoved();
  2858. return;
  2859. }
  2860. if ( subject === null ) {
  2861. return;
  2862. }
  2863. if ( subject instanceof Ci.nsICookie2 === false ) {
  2864. try {
  2865. subject = subject.QueryInterface(Ci.nsICookie2);
  2866. } catch (ex) {
  2867. return;
  2868. }
  2869. }
  2870. if ( reason === 'deleted' ) {
  2871. if ( typeof this.onRemoved === 'function' ) {
  2872. this.onRemoved(new this.CookieEntry(subject));
  2873. }
  2874. return;
  2875. }
  2876. if ( typeof this.onChanged === 'function' ) {
  2877. this.onChanged(new this.CookieEntry(subject));
  2878. }
  2879. };
  2880. /******************************************************************************/
  2881. // Meant and expected to be asynchronous.
  2882. vAPI.cookies.getAll = function(callback) {
  2883. if ( typeof callback !== 'function' ) {
  2884. return;
  2885. }
  2886. var onAsync = function() {
  2887. var out = [];
  2888. var enumerator = Services.cookies.enumerator;
  2889. var ffcookie;
  2890. while ( enumerator.hasMoreElements() ) {
  2891. ffcookie = enumerator.getNext();
  2892. if ( ffcookie instanceof Ci.nsICookie ) {
  2893. out.push(new this.CookieEntry(ffcookie));
  2894. }
  2895. }
  2896. callback(out);
  2897. };
  2898. vAPI.setTimeout(onAsync.bind(this), 0);
  2899. };
  2900. /******************************************************************************/
  2901. vAPI.cookies.remove = function(details, callback) {
  2902. var uri = Services.io.newURI(details.url, null, null);
  2903. var cookies = Services.cookies;
  2904. cookies.remove(uri.asciiHost, details.name, uri.path, false, {});
  2905. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false, {});
  2906. if ( typeof callback === 'function' ) {
  2907. callback({
  2908. domain: uri.asciiHost,
  2909. name: details.name,
  2910. path: uri.path
  2911. });
  2912. }
  2913. };
  2914. /******************************************************************************/
  2915. /******************************************************************************/
  2916. })();
  2917. /******************************************************************************/