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.

3454 lines
107 KiB

9 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
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
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
  1. /*******************************************************************************
  2. uMatrix - a browser extension to block requests.
  3. Copyright (C) 2014-2016 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. 10: 'ping',
  1444. 11: 'xmlhttprequest',
  1445. 12: 'object',
  1446. 14: 'font',
  1447. 15: 'image',
  1448. 16: 'websocket',
  1449. 20: 'xmlhttprequest',
  1450. 21: 'image'
  1451. },
  1452. mimeTypeMap: {
  1453. 'audio': 15,
  1454. 'video': 15
  1455. },
  1456. get componentRegistrar() {
  1457. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  1458. },
  1459. get categoryManager() {
  1460. return Cc['@mozilla.org/categorymanager;1']
  1461. .getService(Ci.nsICategoryManager);
  1462. },
  1463. QueryInterface: (function() {
  1464. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  1465. return XPCOMUtils.generateQI([
  1466. Ci.nsIFactory,
  1467. Ci.nsIObserver,
  1468. Ci.nsIChannelEventSink,
  1469. Ci.nsISupportsWeakReference
  1470. ]);
  1471. })(),
  1472. createInstance: function(outer, iid) {
  1473. if ( outer ) {
  1474. throw Components.results.NS_ERROR_NO_AGGREGATION;
  1475. }
  1476. return this.QueryInterface(iid);
  1477. },
  1478. register: function() {
  1479. this.pendingRingBufferInit();
  1480. // https://developer.mozilla.org/en/docs/Observer_Notifications#HTTP_requests
  1481. Services.obs.addObserver(this, 'http-on-modify-request', true);
  1482. Services.obs.addObserver(this, 'http-on-examine-response', true);
  1483. Services.obs.addObserver(this, 'http-on-examine-cached-response', true);
  1484. // Guard against stale instances not having been unregistered
  1485. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  1486. try {
  1487. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  1488. } catch (ex) {
  1489. console.error('uMatrix> httpObserver > unable to unregister stale instance: ', ex);
  1490. }
  1491. }
  1492. this.componentRegistrar.registerFactory(
  1493. this.classID,
  1494. this.classDescription,
  1495. this.contractID,
  1496. this
  1497. );
  1498. this.categoryManager.addCategoryEntry(
  1499. 'net-channel-event-sinks',
  1500. this.contractID,
  1501. this.contractID,
  1502. false,
  1503. true
  1504. );
  1505. },
  1506. unregister: function() {
  1507. Services.obs.removeObserver(this, 'http-on-modify-request');
  1508. Services.obs.removeObserver(this, 'http-on-examine-response');
  1509. Services.obs.removeObserver(this, 'http-on-examine-cached-response');
  1510. this.componentRegistrar.unregisterFactory(this.classID, this);
  1511. this.categoryManager.deleteCategoryEntry(
  1512. 'net-channel-event-sinks',
  1513. this.contractID,
  1514. false
  1515. );
  1516. },
  1517. PendingRequest: function() {
  1518. this.rawType = 0;
  1519. this.tabId = 0;
  1520. this._key = ''; // key is url, from URI.spec
  1521. },
  1522. // If all work fine, this map should not grow indefinitely. It can have
  1523. // stale items in it, but these will be taken care of when entries in
  1524. // the ring buffer are overwritten.
  1525. pendingURLToIndex: new Map(),
  1526. pendingWritePointer: 0,
  1527. pendingRingBuffer: new Array(256),
  1528. pendingRingBufferInit: function() {
  1529. // Use and reuse pre-allocated PendingRequest objects = less memory
  1530. // churning.
  1531. var i = this.pendingRingBuffer.length;
  1532. while ( i-- ) {
  1533. this.pendingRingBuffer[i] = new this.PendingRequest();
  1534. }
  1535. },
  1536. // Pending request ring buffer:
  1537. // +-------+-------+-------+-------+-------+-------+-------
  1538. // |0 |1 |2 |3 |4 |5 |...
  1539. // +-------+-------+-------+-------+-------+-------+-------
  1540. //
  1541. // URL to ring buffer index map:
  1542. // { k = URL, s = ring buffer indices }
  1543. //
  1544. // s is a string which character codes map to ring buffer indices -- for
  1545. // when the same URL is received multiple times by shouldLoadListener()
  1546. // before the existing one is serviced by the network request observer.
  1547. // I believe the use of a string in lieu of an array reduces memory
  1548. // churning.
  1549. createPendingRequest: function(url) {
  1550. var bucket;
  1551. var i = this.pendingWritePointer;
  1552. this.pendingWritePointer = i + 1 & 255;
  1553. var preq = this.pendingRingBuffer[i];
  1554. var si = String.fromCharCode(i);
  1555. // Cleanup unserviced pending request
  1556. if ( preq._key !== '' ) {
  1557. bucket = this.pendingURLToIndex.get(preq._key);
  1558. if ( bucket.length === 1 ) {
  1559. this.pendingURLToIndex.delete(preq._key);
  1560. } else {
  1561. var pos = bucket.indexOf(si);
  1562. this.pendingURLToIndex.set(preq._key, bucket.slice(0, pos) + bucket.slice(pos + 1));
  1563. }
  1564. }
  1565. bucket = this.pendingURLToIndex.get(url);
  1566. this.pendingURLToIndex.set(url, bucket === undefined ? si : bucket + si);
  1567. preq._key = url;
  1568. return preq;
  1569. },
  1570. lookupPendingRequest: function(url) {
  1571. var bucket = this.pendingURLToIndex.get(url);
  1572. if ( bucket === undefined ) {
  1573. return null;
  1574. }
  1575. var i = bucket.charCodeAt(0);
  1576. if ( bucket.length === 1 ) {
  1577. this.pendingURLToIndex.delete(url);
  1578. } else {
  1579. this.pendingURLToIndex.set(url, bucket.slice(1));
  1580. }
  1581. var preq = this.pendingRingBuffer[i];
  1582. preq._key = ''; // mark as "serviced"
  1583. return preq;
  1584. },
  1585. handleRequest: function(channel, URI, tabId, rawType) {
  1586. var type = this.typeMap[rawType] || 'other';
  1587. var onBeforeRequest = vAPI.net.onBeforeRequest;
  1588. if ( onBeforeRequest.types === null || onBeforeRequest.types.has(type) ) {
  1589. var result = onBeforeRequest.callback({
  1590. parentFrameId: type === 'main_frame' ? -1 : 0,
  1591. tabId: tabId,
  1592. type: type,
  1593. url: URI.asciiSpec
  1594. });
  1595. if ( typeof result === 'object' ) {
  1596. channel.cancel(this.ABORT);
  1597. return true;
  1598. }
  1599. }
  1600. var onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders;
  1601. if ( onBeforeSendHeaders.types === null || onBeforeSendHeaders.types.has(type) ) {
  1602. var requestHeaders = httpRequestHeadersFactory(channel);
  1603. onBeforeSendHeaders.callback({
  1604. parentFrameId: type === 'main_frame' ? -1 : 0,
  1605. requestHeaders: requestHeaders,
  1606. tabId: tabId,
  1607. type: type,
  1608. url: URI.asciiSpec
  1609. });
  1610. requestHeaders.dispose();
  1611. }
  1612. return false;
  1613. },
  1614. channelDataFromChannel: function(channel) {
  1615. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  1616. try {
  1617. return channel.getProperty(this.REQDATAKEY) || null;
  1618. } catch (ex) {
  1619. }
  1620. }
  1621. return null;
  1622. },
  1623. // https://github.com/gorhill/uMatrix/issues/165
  1624. // https://developer.mozilla.org/en-US/Firefox/Releases/3.5/Updating_extensions#Getting_a_load_context_from_a_request
  1625. // Not sure `umatrix:shouldLoad` is still needed, uMatrix does not
  1626. // care about embedded frames topography.
  1627. // Also:
  1628. // https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Limitations_of_chrome_scripts
  1629. tabIdFromChannel: function(channel) {
  1630. var lc;
  1631. try {
  1632. lc = channel.notificationCallbacks.getInterface(Ci.nsILoadContext);
  1633. } catch(ex) {
  1634. }
  1635. if ( !lc ) {
  1636. try {
  1637. lc = channel.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext);
  1638. } catch(ex) {
  1639. }
  1640. if ( !lc ) {
  1641. return vAPI.noTabId;
  1642. }
  1643. }
  1644. if ( lc.topFrameElement ) {
  1645. return tabWatcher.tabIdFromTarget(lc.topFrameElement);
  1646. }
  1647. var win;
  1648. try {
  1649. win = lc.associatedWindow;
  1650. } catch (ex) { }
  1651. if ( !win ) {
  1652. return vAPI.noTabId;
  1653. }
  1654. if ( win.top ) {
  1655. win = win.top;
  1656. }
  1657. var tabBrowser;
  1658. try {
  1659. tabBrowser = getTabBrowser(
  1660. win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation)
  1661. .QueryInterface(Ci.nsIDocShell).rootTreeItem
  1662. .QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow)
  1663. );
  1664. } catch (ex) { }
  1665. if ( !tabBrowser ) {
  1666. return vAPI.noTabId;
  1667. }
  1668. if ( tabBrowser.getBrowserForContentWindow ) {
  1669. return tabWatcher.tabIdFromTarget(tabBrowser.getBrowserForContentWindow(win));
  1670. }
  1671. // Falling back onto _getTabForContentWindow to ensure older versions
  1672. // of Firefox work well.
  1673. return tabBrowser._getTabForContentWindow ?
  1674. tabWatcher.tabIdFromTarget(tabBrowser._getTabForContentWindow(win)) :
  1675. vAPI.noTabId;
  1676. },
  1677. rawtypeFromContentType: function(channel) {
  1678. var mime = channel.contentType;
  1679. if ( !mime ) {
  1680. return 0;
  1681. }
  1682. var pos = mime.indexOf('/');
  1683. if ( pos === -1 ) {
  1684. pos = mime.length;
  1685. }
  1686. return this.mimeTypeMap[mime.slice(0, pos)] || 0;
  1687. },
  1688. observe: function(channel, topic) {
  1689. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  1690. return;
  1691. }
  1692. var URI = channel.URI;
  1693. var channelData = this.channelDataFromChannel(channel);
  1694. if ( topic.lastIndexOf('http-on-examine-', 0) === 0 ) {
  1695. if ( channelData === null ) {
  1696. return;
  1697. }
  1698. var type = this.frameTypeMap[channelData[1]];
  1699. if ( !type ) {
  1700. return;
  1701. }
  1702. topic = 'Content-Security-Policy';
  1703. var result;
  1704. try {
  1705. result = channel.getResponseHeader(topic);
  1706. } catch (ex) {
  1707. result = null;
  1708. }
  1709. result = vAPI.net.onHeadersReceived.callback({
  1710. parentFrameId: type === 'main_frame' ? -1 : 0,
  1711. responseHeaders: result ? [{name: topic, value: result}] : [],
  1712. tabId: channelData[0],
  1713. type: type,
  1714. url: URI.asciiSpec
  1715. });
  1716. if ( result ) {
  1717. channel.setResponseHeader(
  1718. topic,
  1719. result.responseHeaders.pop().value,
  1720. true
  1721. );
  1722. }
  1723. return;
  1724. }
  1725. // http-on-modify-request
  1726. // The channel was previously serviced.
  1727. if ( channelData !== null ) {
  1728. this.handleRequest(channel, URI, channelData[0], channelData[1]);
  1729. return;
  1730. }
  1731. // The channel was never serviced.
  1732. var tabId;
  1733. var pendingRequest = this.lookupPendingRequest(URI.asciiSpec);
  1734. var rawType = 1;
  1735. var loadInfo = channel.loadInfo;
  1736. // https://github.com/gorhill/uMatrix/issues/390#issuecomment-155717004
  1737. if ( loadInfo ) {
  1738. rawType = loadInfo.externalContentPolicyType !== undefined ?
  1739. loadInfo.externalContentPolicyType :
  1740. loadInfo.contentPolicyType;
  1741. if ( !rawType ) {
  1742. rawType = 1;
  1743. }
  1744. }
  1745. if ( pendingRequest !== null ) {
  1746. tabId = pendingRequest.tabId;
  1747. // https://github.com/gorhill/uBlock/issues/654
  1748. // Use the request type from the HTTP observer point of view.
  1749. if ( rawType !== 1 ) {
  1750. pendingRequest.rawType = rawType;
  1751. } else {
  1752. rawType = pendingRequest.rawType;
  1753. }
  1754. } else {
  1755. tabId = this.tabIdFromChannel(channel);
  1756. }
  1757. if ( this.handleRequest(channel, URI, tabId, rawType) ) {
  1758. return;
  1759. }
  1760. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1761. return;
  1762. }
  1763. // Carry data for behind-the-scene redirects
  1764. channel.setProperty(this.REQDATAKEY, [tabId, rawType]);
  1765. },
  1766. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1767. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1768. // If error thrown, the redirect will fail
  1769. try {
  1770. var URI = newChannel.URI;
  1771. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1772. return;
  1773. }
  1774. if ( newChannel instanceof Ci.nsIWritablePropertyBag === false ) {
  1775. return;
  1776. }
  1777. var channelData = this.channelDataFromChannel(oldChannel);
  1778. if ( channelData === null ) {
  1779. return;
  1780. }
  1781. // Carry the data on in case of multiple redirects
  1782. newChannel.setProperty(this.REQDATAKEY, channelData);
  1783. } catch (ex) {
  1784. // console.error(ex);
  1785. } finally {
  1786. callback.onRedirectVerifyCallback(this.ACCEPT);
  1787. }
  1788. }
  1789. };
  1790. /******************************************************************************/
  1791. vAPI.net = {};
  1792. /******************************************************************************/
  1793. vAPI.net.registerListeners = function() {
  1794. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1795. new Set(this.onBeforeRequest.types) :
  1796. null;
  1797. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1798. new Set(this.onBeforeSendHeaders.types) :
  1799. null;
  1800. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  1801. var shouldLoadListener = function(e) {
  1802. var details = e.data;
  1803. var pendingReq = httpObserver.createPendingRequest(details.url);
  1804. pendingReq.rawType = details.rawType;
  1805. pendingReq.tabId = tabWatcher.tabIdFromTarget(e.target);
  1806. };
  1807. // https://github.com/gorhill/uMatrix/issues/200
  1808. // We need this only for Firefox 34 and less: the tab id is derived from
  1809. // the origin of the message.
  1810. if ( !vAPI.modernFirefox ) {
  1811. vAPI.messaging.globalMessageManager.addMessageListener(
  1812. shouldLoadListenerMessageName,
  1813. shouldLoadListener
  1814. );
  1815. }
  1816. httpObserver.register();
  1817. cleanupTasks.push(function() {
  1818. if ( !vAPI.modernFirefox ) {
  1819. vAPI.messaging.globalMessageManager.removeMessageListener(
  1820. shouldLoadListenerMessageName,
  1821. shouldLoadListener
  1822. );
  1823. }
  1824. httpObserver.unregister();
  1825. });
  1826. };
  1827. /******************************************************************************/
  1828. /******************************************************************************/
  1829. vAPI.toolbarButton = {
  1830. id: location.host + '-button',
  1831. type: 'view',
  1832. viewId: location.host + '-panel',
  1833. label: vAPI.app.name,
  1834. tooltiptext: vAPI.app.name,
  1835. tabs: {/*tabId: {badge: 0, img: boolean}*/},
  1836. init: null,
  1837. codePath: ''
  1838. };
  1839. /******************************************************************************/
  1840. // Non-Fennec: common code paths.
  1841. (function() {
  1842. if ( vAPI.fennec ) {
  1843. return;
  1844. }
  1845. var tbb = vAPI.toolbarButton;
  1846. var popupCommittedWidth = 0;
  1847. var popupCommittedHeight = 0;
  1848. tbb.onViewShowing = function({target}) {
  1849. popupCommittedWidth = popupCommittedHeight = 0;
  1850. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1851. };
  1852. tbb.onViewHiding = function({target}) {
  1853. target.parentNode.style.maxWidth = '';
  1854. target.firstChild.setAttribute('src', 'about:blank');
  1855. };
  1856. tbb.updateState = function(win, tabId) {
  1857. var button = win.document.getElementById(this.id);
  1858. if ( !button ) {
  1859. return;
  1860. }
  1861. var icon = this.tabs[tabId];
  1862. button.setAttribute('badge', icon && icon.badge || '');
  1863. button.classList.toggle('off', !icon || !icon.img);
  1864. var iconId = icon && icon.img ? icon.img : 'off';
  1865. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1866. button.style.listStyleImage = icon;
  1867. };
  1868. tbb.populatePanel = function(doc, panel) {
  1869. panel.setAttribute('id', this.viewId);
  1870. var iframe = doc.createElement('iframe');
  1871. iframe.setAttribute('type', 'content');
  1872. panel.appendChild(iframe);
  1873. var toPx = function(pixels) {
  1874. return pixels.toString() + 'px';
  1875. };
  1876. var scrollBarWidth = 0;
  1877. var resizeTimer = null;
  1878. var resizePopupDelayed = function(attempts) {
  1879. if ( resizeTimer !== null ) {
  1880. return false;
  1881. }
  1882. // Sanity check
  1883. attempts = (attempts || 0) + 1;
  1884. if ( attempts > 1/*000*/ ) {
  1885. //console.error('uMatrix> resizePopupDelayed: giving up after too many attempts');
  1886. return false;
  1887. }
  1888. resizeTimer = vAPI.setTimeout(resizePopup, 10, attempts);
  1889. return true;
  1890. };
  1891. var resizePopup = function(attempts) {
  1892. resizeTimer = null;
  1893. panel.parentNode.style.maxWidth = 'none';
  1894. var body = iframe.contentDocument.body;
  1895. // https://github.com/gorhill/uMatrix/issues/301
  1896. // Don't resize if committed size did not change.
  1897. if (
  1898. popupCommittedWidth === body.clientWidth &&
  1899. popupCommittedHeight === body.clientHeight
  1900. ) {
  1901. return;
  1902. }
  1903. // We set a limit for height
  1904. var height = Math.min(body.clientHeight, 600);
  1905. // https://github.com/chrisaljoudi/uBlock/issues/730
  1906. // Voodoo programming: this recipe works
  1907. panel.style.setProperty('height', toPx(height));
  1908. iframe.style.setProperty('height', toPx(height));
  1909. // Adjust width for presence/absence of vertical scroll bar which may
  1910. // have appeared as a result of last operation.
  1911. var contentWindow = iframe.contentWindow;
  1912. var width = body.clientWidth;
  1913. if ( contentWindow.scrollMaxY !== 0 ) {
  1914. width += scrollBarWidth;
  1915. }
  1916. panel.style.setProperty('width', toPx(width));
  1917. // scrollMaxX should always be zero once we know the scrollbar width
  1918. if ( contentWindow.scrollMaxX !== 0 ) {
  1919. scrollBarWidth = contentWindow.scrollMaxX;
  1920. width += scrollBarWidth;
  1921. panel.style.setProperty('width', toPx(width));
  1922. }
  1923. if ( iframe.clientHeight !== height || panel.clientWidth !== width ) {
  1924. if ( resizePopupDelayed(attempts) ) {
  1925. return;
  1926. }
  1927. // resizePopupDelayed won't be called again, so commit
  1928. // dimentsions.
  1929. }
  1930. popupCommittedWidth = body.clientWidth;
  1931. popupCommittedHeight = body.clientHeight;
  1932. };
  1933. var onResizeRequested = function() {
  1934. var body = iframe.contentDocument.body;
  1935. if ( body.getAttribute('data-resize-popup') !== 'true' ) {
  1936. return;
  1937. }
  1938. body.removeAttribute('data-resize-popup');
  1939. resizePopupDelayed();
  1940. };
  1941. var onPopupReady = function() {
  1942. var win = this.contentWindow;
  1943. if ( !win || win.location.host !== location.host ) {
  1944. return;
  1945. }
  1946. if ( typeof tbb.onBeforePopupReady === 'function' ) {
  1947. tbb.onBeforePopupReady.call(this);
  1948. }
  1949. resizePopupDelayed();
  1950. var body = win.document.body;
  1951. body.removeAttribute('data-resize-popup');
  1952. var mutationObserver = new win.MutationObserver(onResizeRequested);
  1953. mutationObserver.observe(body, {
  1954. attributes: true,
  1955. attributeFilter: [ 'data-resize-popup' ]
  1956. });
  1957. };
  1958. iframe.addEventListener('load', onPopupReady, true);
  1959. };
  1960. })();
  1961. /******************************************************************************/
  1962. // Firefox 28 and less
  1963. (function() {
  1964. var tbb = vAPI.toolbarButton;
  1965. if ( tbb.init !== null ) {
  1966. return;
  1967. }
  1968. var CustomizableUI = null;
  1969. var forceLegacyToolbarButton = vAPI.localStorage.getBool('forceLegacyToolbarButton');
  1970. if ( !forceLegacyToolbarButton ) {
  1971. try {
  1972. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1973. } catch (ex) {
  1974. }
  1975. }
  1976. if ( CustomizableUI !== null ) {
  1977. return;
  1978. }
  1979. tbb.codePath = 'legacy';
  1980. tbb.id = 'umatrix-legacy-button'; // NOTE: must match legacy-toolbar-button.css
  1981. tbb.viewId = tbb.id + '-panel';
  1982. var styleSheetUri = null;
  1983. var createToolbarButton = function(window) {
  1984. var document = window.document;
  1985. var toolbarButton = document.createElement('toolbarbutton');
  1986. toolbarButton.setAttribute('id', tbb.id);
  1987. // type = panel would be more accurate, but doesn't look as good
  1988. toolbarButton.setAttribute('type', 'menu');
  1989. toolbarButton.setAttribute('removable', 'true');
  1990. toolbarButton.setAttribute('class', 'toolbarbutton-1 chromeclass-toolbar-additional');
  1991. toolbarButton.setAttribute('label', tbb.label);
  1992. toolbarButton.setAttribute('tooltiptext', tbb.label);
  1993. var toolbarButtonPanel = document.createElement('panel');
  1994. // NOTE: Setting level to parent breaks the popup for PaleMoon under
  1995. // linux (mouse pointer misaligned with content). For some reason.
  1996. // toolbarButtonPanel.setAttribute('level', 'parent');
  1997. tbb.populatePanel(document, toolbarButtonPanel);
  1998. toolbarButtonPanel.addEventListener('popupshowing', tbb.onViewShowing);
  1999. toolbarButtonPanel.addEventListener('popuphiding', tbb.onViewHiding);
  2000. toolbarButton.appendChild(toolbarButtonPanel);
  2001. return toolbarButton;
  2002. };
  2003. var addLegacyToolbarButton = function(window) {
  2004. // uMatrix's stylesheet lazily added.
  2005. if ( styleSheetUri === null ) {
  2006. var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
  2007. .getService(Ci.nsIStyleSheetService);
  2008. styleSheetUri = Services.io.newURI(vAPI.getURL("css/legacy-toolbar-button.css"), null, null);
  2009. // Register global so it works in all windows, including palette
  2010. if ( !sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  2011. sss.loadAndRegisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  2012. }
  2013. }
  2014. var document = window.document;
  2015. // https://github.com/gorhill/uMatrix/issues/357
  2016. // Already installed?
  2017. if ( document.getElementById(tbb.id) !== null ) {
  2018. return;
  2019. }
  2020. var toolbox = document.getElementById('navigator-toolbox') ||
  2021. document.getElementById('mail-toolbox');
  2022. if ( toolbox === null ) {
  2023. return;
  2024. }
  2025. var toolbarButton = createToolbarButton(window);
  2026. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/toolbarpalette
  2027. var palette = toolbox.palette;
  2028. if ( palette && palette.querySelector('#' + tbb.id) === null ) {
  2029. palette.appendChild(toolbarButton);
  2030. }
  2031. // Find the place to put the button.
  2032. // Pale Moon: `toolbox.externalToolbars` can be undefined. Seen while
  2033. // testing popup test number 3:
  2034. // http://raymondhill.net/ublock/popup.html
  2035. var toolbars = toolbox.externalToolbars ? toolbox.externalToolbars.slice() : [];
  2036. for ( var child of toolbox.children ) {
  2037. if ( child.localName === 'toolbar' ) {
  2038. toolbars.push(child);
  2039. }
  2040. }
  2041. for ( var toolbar of toolbars ) {
  2042. var currentsetString = toolbar.getAttribute('currentset');
  2043. if ( !currentsetString ) {
  2044. continue;
  2045. }
  2046. var currentset = currentsetString.split(/\s*,\s*/);
  2047. var index = currentset.indexOf(tbb.id);
  2048. if ( index === -1 ) {
  2049. continue;
  2050. }
  2051. // This can occur with Pale Moon:
  2052. // "TypeError: toolbar.insertItem is not a function"
  2053. if ( typeof toolbar.insertItem !== 'function' ) {
  2054. continue;
  2055. }
  2056. // Found our button on this toolbar - but where on it?
  2057. var before = null;
  2058. for ( var i = index + 1; i < currentset.length; i++ ) {
  2059. before = toolbar.querySelector('[id="' + currentset[i] + '"]');
  2060. if ( before !== null ) {
  2061. break;
  2062. }
  2063. }
  2064. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Method/insertItem
  2065. toolbar.insertItem(tbb.id, before);
  2066. break;
  2067. }
  2068. // https://github.com/gorhill/uBlock/issues/763
  2069. // We are done if our toolbar button is already installed in one of the
  2070. // toolbar.
  2071. if ( palette !== null && toolbarButton.parentElement !== palette ) {
  2072. return;
  2073. }
  2074. // No button yet so give it a default location. If forcing the button,
  2075. // just put in in the palette rather than on any specific toolbar (who
  2076. // knows what toolbars will be available or visible!)
  2077. var navbar = document.getElementById('nav-bar');
  2078. if ( navbar !== null && !vAPI.localStorage.getBool('legacyToolbarButtonAdded') ) {
  2079. // https://github.com/gorhill/uBlock/issues/264
  2080. // Find a child customizable palette, if any.
  2081. navbar = navbar.querySelector('.customization-target') || navbar;
  2082. navbar.appendChild(toolbarButton);
  2083. navbar.setAttribute('currentset', navbar.currentSet);
  2084. document.persist(navbar.id, 'currentset');
  2085. vAPI.localStorage.setBool('legacyToolbarButtonAdded', 'true');
  2086. }
  2087. };
  2088. var canAddLegacyToolbarButton = function(window) {
  2089. var document = window.document;
  2090. if (
  2091. !document ||
  2092. document.readyState !== 'complete' ||
  2093. document.getElementById('nav-bar') === null
  2094. ) {
  2095. return false;
  2096. }
  2097. var toolbox = document.getElementById('navigator-toolbox') ||
  2098. document.getElementById('mail-toolbox');
  2099. return toolbox !== null && !!toolbox.palette;
  2100. };
  2101. var onPopupCloseRequested = function({target}) {
  2102. var document = target.ownerDocument;
  2103. if ( !document ) {
  2104. return;
  2105. }
  2106. var toolbarButtonPanel = document.getElementById(tbb.viewId);
  2107. if ( toolbarButtonPanel === null ) {
  2108. return;
  2109. }
  2110. // `hidePopup` reported as not existing while testing legacy button
  2111. // on FF 41.0.2.
  2112. // https://bugzilla.mozilla.org/show_bug.cgi?id=1151796
  2113. if ( typeof toolbarButtonPanel.hidePopup === 'function' ) {
  2114. toolbarButtonPanel.hidePopup();
  2115. }
  2116. };
  2117. var shutdown = function() {
  2118. for ( var win of winWatcher.getWindows() ) {
  2119. var toolbarButton = win.document.getElementById(tbb.id);
  2120. if ( toolbarButton ) {
  2121. toolbarButton.parentNode.removeChild(toolbarButton);
  2122. }
  2123. }
  2124. if ( styleSheetUri !== null ) {
  2125. var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
  2126. .getService(Ci.nsIStyleSheetService);
  2127. if ( sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  2128. sss.unregisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  2129. }
  2130. styleSheetUri = null;
  2131. }
  2132. vAPI.messaging.globalMessageManager.removeMessageListener(
  2133. location.host + ':closePopup',
  2134. onPopupCloseRequested
  2135. );
  2136. };
  2137. tbb.attachToNewWindow = function(win) {
  2138. deferUntil(
  2139. canAddLegacyToolbarButton.bind(null, win),
  2140. addLegacyToolbarButton.bind(null, win)
  2141. );
  2142. };
  2143. tbb.init = function() {
  2144. vAPI.messaging.globalMessageManager.addMessageListener(
  2145. location.host + ':closePopup',
  2146. onPopupCloseRequested
  2147. );
  2148. cleanupTasks.push(shutdown);
  2149. };
  2150. })();
  2151. /******************************************************************************/
  2152. // Firefox Australis < 36.
  2153. (function() {
  2154. var tbb = vAPI.toolbarButton;
  2155. if ( tbb.init !== null ) {
  2156. return;
  2157. }
  2158. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') >= 0 ) {
  2159. return null;
  2160. }
  2161. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  2162. return null;
  2163. }
  2164. var CustomizableUI = null;
  2165. try {
  2166. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  2167. } catch (ex) {
  2168. }
  2169. if ( CustomizableUI === null ) {
  2170. return;
  2171. }
  2172. tbb.codePath = 'australis';
  2173. tbb.CustomizableUI = CustomizableUI;
  2174. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  2175. var styleURI = null;
  2176. var onPopupCloseRequested = function({target}) {
  2177. if ( typeof tbb.closePopup === 'function' ) {
  2178. tbb.closePopup(target);
  2179. }
  2180. };
  2181. var shutdown = function() {
  2182. CustomizableUI.destroyWidget(tbb.id);
  2183. for ( var win of winWatcher.getWindows() ) {
  2184. var panel = win.document.getElementById(tbb.viewId);
  2185. panel.parentNode.removeChild(panel);
  2186. win.QueryInterface(Ci.nsIInterfaceRequestor)
  2187. .getInterface(Ci.nsIDOMWindowUtils)
  2188. .removeSheet(styleURI, 1);
  2189. }
  2190. vAPI.messaging.globalMessageManager.removeMessageListener(
  2191. location.host + ':closePopup',
  2192. onPopupCloseRequested
  2193. );
  2194. };
  2195. tbb.onBeforeCreated = function(doc) {
  2196. var panel = doc.createElement('panelview');
  2197. this.populatePanel(doc, panel);
  2198. doc.getElementById('PanelUI-multiView').appendChild(panel);
  2199. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  2200. .getInterface(Ci.nsIDOMWindowUtils)
  2201. .loadSheet(styleURI, 1);
  2202. };
  2203. tbb.onBeforePopupReady = function() {
  2204. // https://github.com/gorhill/uBlock/issues/83
  2205. // Add `portrait` class if width is constrained.
  2206. try {
  2207. this.contentDocument.body.classList.toggle(
  2208. 'portrait',
  2209. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  2210. );
  2211. } catch (ex) {
  2212. /* noop */
  2213. }
  2214. };
  2215. tbb.init = function() {
  2216. vAPI.messaging.globalMessageManager.addMessageListener(
  2217. location.host + ':closePopup',
  2218. onPopupCloseRequested
  2219. );
  2220. var style = [
  2221. '#' + this.id + '.off {',
  2222. 'list-style-image: url(',
  2223. vAPI.getURL('img/browsericons/icon19-off.png'),
  2224. ');',
  2225. '}',
  2226. '#' + this.id + ' {',
  2227. 'list-style-image: url(',
  2228. vAPI.getURL('img/browsericons/icon19.png'),
  2229. ');',
  2230. '}',
  2231. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  2232. 'width: 160px;',
  2233. 'height: 290px;',
  2234. 'overflow: hidden !important;',
  2235. '}',
  2236. '#' + this.id + '[badge]:not([badge=""])::after {',
  2237. 'position: absolute;',
  2238. 'margin-left: -16px;',
  2239. 'margin-top: 3px;',
  2240. 'padding: 1px 2px;',
  2241. 'font-size: 9px;',
  2242. 'font-weight: bold;',
  2243. 'color: #fff;',
  2244. 'background: #000;',
  2245. 'content: attr(badge);',
  2246. '}'
  2247. ];
  2248. styleURI = Services.io.newURI(
  2249. 'data:text/css,' + encodeURIComponent(style.join('')),
  2250. null,
  2251. null
  2252. );
  2253. this.closePopup = function(tabBrowser) {
  2254. CustomizableUI.hidePanelForNode(
  2255. tabBrowser.ownerDocument.getElementById(this.viewId)
  2256. );
  2257. };
  2258. CustomizableUI.createWidget(this);
  2259. cleanupTasks.push(shutdown);
  2260. };
  2261. })();
  2262. /******************************************************************************/
  2263. // Firefox Australis >= 36.
  2264. (function() {
  2265. var tbb = vAPI.toolbarButton;
  2266. if ( tbb.init !== null ) {
  2267. return;
  2268. }
  2269. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') < 0 ) {
  2270. return null;
  2271. }
  2272. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  2273. return null;
  2274. }
  2275. var CustomizableUI = null;
  2276. try {
  2277. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  2278. } catch (ex) {
  2279. }
  2280. if ( CustomizableUI === null ) {
  2281. return null;
  2282. }
  2283. tbb.codePath = 'australis';
  2284. tbb.CustomizableUI = CustomizableUI;
  2285. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  2286. var CUIEvents = {};
  2287. var badgeCSSRules = [
  2288. 'background: #000',
  2289. 'color: #fff'
  2290. ].join(';');
  2291. var updateBadgeStyle = function() {
  2292. for ( var win of winWatcher.getWindows() ) {
  2293. var button = win.document.getElementById(tbb.id);
  2294. if ( button === null ) {
  2295. continue;
  2296. }
  2297. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  2298. button,
  2299. 'class',
  2300. 'toolbarbutton-badge'
  2301. );
  2302. if ( !badge ) {
  2303. continue;
  2304. }
  2305. badge.style.cssText = badgeCSSRules;
  2306. }
  2307. };
  2308. var updateBadge = function() {
  2309. var wId = tbb.id;
  2310. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  2311. for ( var win of winWatcher.getWindows() ) {
  2312. var button = win.document.getElementById(wId);
  2313. if ( button === null ) {
  2314. continue;
  2315. }
  2316. if ( buttonInPanel ) {
  2317. button.classList.remove('badged-button');
  2318. continue;
  2319. }
  2320. button.classList.add('badged-button');
  2321. }
  2322. if ( buttonInPanel ) {
  2323. return;
  2324. }
  2325. // Anonymous elements need some time to be reachable
  2326. vAPI.setTimeout(updateBadgeStyle, 250);
  2327. }.bind(CUIEvents);
  2328. // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/CustomizableUI.jsm#Listeners
  2329. CUIEvents.onCustomizeEnd = updateBadge;
  2330. CUIEvents.onWidgetAdded = updateBadge;
  2331. CUIEvents.onWidgetUnderflow = updateBadge;
  2332. var onPopupCloseRequested = function({target}) {
  2333. if ( typeof tbb.closePopup === 'function' ) {
  2334. tbb.closePopup(target);
  2335. }
  2336. };
  2337. var shutdown = function() {
  2338. for ( var win of winWatcher.getWindows() ) {
  2339. var panel = win.document.getElementById(tbb.viewId);
  2340. if ( panel !== null && panel.parentNode !== null ) {
  2341. panel.parentNode.removeChild(panel);
  2342. }
  2343. win.QueryInterface(Ci.nsIInterfaceRequestor)
  2344. .getInterface(Ci.nsIDOMWindowUtils)
  2345. .removeSheet(styleURI, 1);
  2346. }
  2347. CustomizableUI.removeListener(CUIEvents);
  2348. CustomizableUI.destroyWidget(tbb.id);
  2349. vAPI.messaging.globalMessageManager.removeMessageListener(
  2350. location.host + ':closePopup',
  2351. onPopupCloseRequested
  2352. );
  2353. };
  2354. var styleURI = null;
  2355. tbb.onBeforeCreated = function(doc) {
  2356. var panel = doc.createElement('panelview');
  2357. this.populatePanel(doc, panel);
  2358. doc.getElementById('PanelUI-multiView').appendChild(panel);
  2359. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  2360. .getInterface(Ci.nsIDOMWindowUtils)
  2361. .loadSheet(styleURI, 1);
  2362. };
  2363. tbb.onCreated = function(button) {
  2364. button.setAttribute('badge', '');
  2365. vAPI.setTimeout(updateBadge, 250);
  2366. };
  2367. tbb.onBeforePopupReady = function() {
  2368. // https://github.com/gorhill/uBlock/issues/83
  2369. // Add `portrait` class if width is constrained.
  2370. try {
  2371. this.contentDocument.body.classList.toggle(
  2372. 'portrait',
  2373. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  2374. );
  2375. } catch (ex) {
  2376. /* noop */
  2377. }
  2378. };
  2379. tbb.closePopup = function(tabBrowser) {
  2380. CustomizableUI.hidePanelForNode(
  2381. tabBrowser.ownerDocument.getElementById(tbb.viewId)
  2382. );
  2383. };
  2384. tbb.init = function() {
  2385. vAPI.messaging.globalMessageManager.addMessageListener(
  2386. location.host + ':closePopup',
  2387. onPopupCloseRequested
  2388. );
  2389. CustomizableUI.addListener(CUIEvents);
  2390. var style = [
  2391. '#' + this.id + '.off {',
  2392. 'list-style-image: url(',
  2393. vAPI.getURL('img/browsericons/icon19-off.png'),
  2394. ');',
  2395. '}',
  2396. '#' + this.id + ' {',
  2397. 'list-style-image: url(',
  2398. vAPI.getURL('img/browsericons/icon19-19.png'),
  2399. ');',
  2400. '}',
  2401. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  2402. 'width: 160px;',
  2403. 'height: 290px;',
  2404. 'overflow: hidden !important;',
  2405. '}'
  2406. ];
  2407. styleURI = Services.io.newURI(
  2408. 'data:text/css,' + encodeURIComponent(style.join('')),
  2409. null,
  2410. null
  2411. );
  2412. CustomizableUI.createWidget(this);
  2413. cleanupTasks.push(shutdown);
  2414. };
  2415. })();
  2416. /******************************************************************************/
  2417. // No toolbar button.
  2418. (function() {
  2419. // Just to ensure the number of cleanup tasks is as expected: toolbar
  2420. // button code is one single cleanup task regardless of platform.
  2421. if ( vAPI.toolbarButton.init === null ) {
  2422. cleanupTasks.push(function(){});
  2423. }
  2424. })();
  2425. /******************************************************************************/
  2426. if ( vAPI.toolbarButton.init !== null ) {
  2427. vAPI.toolbarButton.init();
  2428. }
  2429. /******************************************************************************/
  2430. /******************************************************************************/
  2431. vAPI.contextMenu = {
  2432. contextMap: {
  2433. frame: 'inFrame',
  2434. link: 'onLink',
  2435. image: 'onImage',
  2436. audio: 'onAudio',
  2437. video: 'onVideo',
  2438. editable: 'onEditableArea'
  2439. }
  2440. };
  2441. /******************************************************************************/
  2442. vAPI.contextMenu.displayMenuItem = function({target}) {
  2443. var doc = target.ownerDocument;
  2444. var gContextMenu = doc.defaultView.gContextMenu;
  2445. if ( !gContextMenu.browser ) {
  2446. return;
  2447. }
  2448. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  2449. var currentURI = gContextMenu.browser.currentURI;
  2450. // https://github.com/chrisaljoudi/uBlock/issues/105
  2451. // TODO: Should the element picker works on any kind of pages?
  2452. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  2453. menuitem.setAttribute('hidden', true);
  2454. return;
  2455. }
  2456. var ctx = vAPI.contextMenu.contexts;
  2457. if ( !ctx ) {
  2458. menuitem.setAttribute('hidden', false);
  2459. return;
  2460. }
  2461. var ctxMap = vAPI.contextMenu.contextMap;
  2462. for ( var context of ctx ) {
  2463. if (
  2464. context === 'page' &&
  2465. !gContextMenu.onLink &&
  2466. !gContextMenu.onImage &&
  2467. !gContextMenu.onEditableArea &&
  2468. !gContextMenu.inFrame &&
  2469. !gContextMenu.onVideo &&
  2470. !gContextMenu.onAudio
  2471. ) {
  2472. menuitem.setAttribute('hidden', false);
  2473. return;
  2474. }
  2475. if (
  2476. ctxMap.hasOwnProperty(context) &&
  2477. gContextMenu[ctxMap[context]]
  2478. ) {
  2479. menuitem.setAttribute('hidden', false);
  2480. return;
  2481. }
  2482. }
  2483. menuitem.setAttribute('hidden', true);
  2484. };
  2485. /******************************************************************************/
  2486. vAPI.contextMenu.register = (function() {
  2487. var register = function(doc) {
  2488. if ( !this.menuItemId ) {
  2489. return;
  2490. }
  2491. // Already installed?
  2492. if ( doc.getElementById(this.menuItemId) !== null ) {
  2493. return;
  2494. }
  2495. var contextMenu = doc.getElementById('contentAreaContextMenu');
  2496. var menuitem = doc.createElement('menuitem');
  2497. menuitem.setAttribute('id', this.menuItemId);
  2498. menuitem.setAttribute('label', this.menuLabel);
  2499. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  2500. menuitem.setAttribute('class', 'menuitem-iconic');
  2501. menuitem.addEventListener('command', this.onCommand);
  2502. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  2503. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  2504. };
  2505. // https://github.com/gorhill/uBlock/issues/906
  2506. // Be sure document.readyState is 'complete': it could happen at launch
  2507. // time that we are called by vAPI.contextMenu.create() directly before
  2508. // the environment is properly initialized.
  2509. var registerSafely = function(doc, tryCount) {
  2510. if ( doc.readyState === 'complete' ) {
  2511. register.call(this, doc);
  2512. return;
  2513. }
  2514. if ( typeof tryCount !== 'number' ) {
  2515. tryCount = 0;
  2516. }
  2517. tryCount += 1;
  2518. if ( tryCount < 8 ) {
  2519. vAPI.setTimeout(registerSafely.bind(this, doc, tryCount), 200);
  2520. }
  2521. };
  2522. return registerSafely;
  2523. })();
  2524. /******************************************************************************/
  2525. vAPI.contextMenu.unregister = function(doc) {
  2526. if ( !this.menuItemId ) {
  2527. return;
  2528. }
  2529. var menuitem = doc.getElementById(this.menuItemId);
  2530. if ( menuitem === null ) {
  2531. return;
  2532. }
  2533. var contextMenu = menuitem.parentNode;
  2534. menuitem.removeEventListener('command', this.onCommand);
  2535. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  2536. contextMenu.removeChild(menuitem);
  2537. };
  2538. /******************************************************************************/
  2539. vAPI.contextMenu.create = function(details, callback) {
  2540. this.menuItemId = details.id;
  2541. this.menuLabel = details.title;
  2542. this.contexts = details.contexts;
  2543. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  2544. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  2545. } else {
  2546. // default in Chrome
  2547. this.contexts = ['page'];
  2548. }
  2549. this.onCommand = function() {
  2550. var gContextMenu = getOwnerWindow(this).gContextMenu;
  2551. var details = {
  2552. menuItemId: this.id
  2553. };
  2554. if ( gContextMenu.inFrame ) {
  2555. details.tagName = 'iframe';
  2556. // Probably won't work with e10s
  2557. details.frameUrl = gContextMenu.focusedWindow.location.href;
  2558. } else if ( gContextMenu.onImage ) {
  2559. details.tagName = 'img';
  2560. details.srcUrl = gContextMenu.mediaURL;
  2561. } else if ( gContextMenu.onAudio ) {
  2562. details.tagName = 'audio';
  2563. details.srcUrl = gContextMenu.mediaURL;
  2564. } else if ( gContextMenu.onVideo ) {
  2565. details.tagName = 'video';
  2566. details.srcUrl = gContextMenu.mediaURL;
  2567. } else if ( gContextMenu.onLink ) {
  2568. details.tagName = 'a';
  2569. details.linkUrl = gContextMenu.linkURL;
  2570. }
  2571. callback(details, {
  2572. id: tabWatcher.tabIdFromTarget(gContextMenu.browser),
  2573. url: gContextMenu.browser.currentURI.asciiSpec
  2574. });
  2575. };
  2576. for ( var win of winWatcher.getWindows() ) {
  2577. this.register(win.document);
  2578. }
  2579. };
  2580. /******************************************************************************/
  2581. vAPI.contextMenu.remove = function() {
  2582. for ( var win of winWatcher.getWindows() ) {
  2583. this.unregister(win.document);
  2584. }
  2585. this.menuItemId = null;
  2586. this.menuLabel = null;
  2587. this.contexts = null;
  2588. this.onCommand = null;
  2589. };
  2590. /******************************************************************************/
  2591. /******************************************************************************/
  2592. var optionsObserver = (function() {
  2593. var addonId = 'uMatrix@raymondhill.net';
  2594. var commandHandler = function() {
  2595. switch ( this.id ) {
  2596. case 'showDashboardButton':
  2597. vAPI.tabs.open({ url: 'dashboard.html', index: -1 });
  2598. break;
  2599. case 'showLoggerButton':
  2600. vAPI.tabs.open({ url: 'logger-ui.html', index: -1 });
  2601. break;
  2602. default:
  2603. break;
  2604. }
  2605. };
  2606. var setupOptionsButton = function(doc, id) {
  2607. var button = doc.getElementById(id);
  2608. if ( button === null ) {
  2609. return;
  2610. }
  2611. button.addEventListener('command', commandHandler);
  2612. button.label = vAPI.i18n(id);
  2613. };
  2614. var setupOptionsButtons = function(doc) {
  2615. setupOptionsButton(doc, 'showDashboardButton');
  2616. setupOptionsButton(doc, 'showLoggerButton');
  2617. };
  2618. var observer = {
  2619. observe: function(doc, topic, id) {
  2620. if ( id !== addonId ) {
  2621. return;
  2622. }
  2623. setupOptionsButtons(doc);
  2624. }
  2625. };
  2626. // https://github.com/gorhill/uBlock/issues/948
  2627. // Older versions of Firefox can throw here when looking up `currentURI`.
  2628. var canInit = function() {
  2629. try {
  2630. var tabBrowser = tabWatcher.currentBrowser();
  2631. return tabBrowser &&
  2632. tabBrowser.currentURI &&
  2633. tabBrowser.currentURI.spec === 'about:addons' &&
  2634. tabBrowser.contentDocument &&
  2635. tabBrowser.contentDocument.readyState === 'complete';
  2636. } catch (ex) {
  2637. }
  2638. };
  2639. // Manually add the buttons if the `about:addons` page is already opened.
  2640. var init = function() {
  2641. if ( canInit() ) {
  2642. setupOptionsButtons(tabWatcher.currentBrowser().contentDocument);
  2643. }
  2644. };
  2645. var unregister = function() {
  2646. Services.obs.removeObserver(observer, 'addon-options-displayed');
  2647. };
  2648. var register = function() {
  2649. Services.obs.addObserver(observer, 'addon-options-displayed', false);
  2650. cleanupTasks.push(unregister);
  2651. deferUntil(canInit, init, { next: 463 });
  2652. };
  2653. return {
  2654. register: register,
  2655. unregister: unregister
  2656. };
  2657. })();
  2658. optionsObserver.register();
  2659. /******************************************************************************/
  2660. /******************************************************************************/
  2661. vAPI.lastError = function() {
  2662. return null;
  2663. };
  2664. /******************************************************************************/
  2665. /******************************************************************************/
  2666. // This is called only once, when everything has been loaded in memory after
  2667. // the extension was launched. It can be used to inject content scripts
  2668. // in already opened web pages, to remove whatever nuisance could make it to
  2669. // the web pages before uBlock was ready.
  2670. vAPI.onLoadAllCompleted = function() {
  2671. for ( var browser of tabWatcher.browsers() ) {
  2672. browser.messageManager.sendAsyncMessage(
  2673. location.host + '-load-completed'
  2674. );
  2675. }
  2676. };
  2677. /******************************************************************************/
  2678. /******************************************************************************/
  2679. // Likelihood is that we do not have to punycode: given punycode overhead,
  2680. // it's faster to check and skip than do it unconditionally all the time.
  2681. var punycodeHostname = punycode.toASCII;
  2682. var isNotASCII = /[^\x21-\x7F]/;
  2683. vAPI.punycodeHostname = function(hostname) {
  2684. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  2685. };
  2686. vAPI.punycodeURL = function(url) {
  2687. if ( isNotASCII.test(url) ) {
  2688. return Services.io.newURI(url, null, null).asciiSpec;
  2689. }
  2690. return url;
  2691. };
  2692. /******************************************************************************/
  2693. /******************************************************************************/
  2694. vAPI.cloud = (function() {
  2695. var extensionBranchPath = 'extensions.' + location.host;
  2696. var cloudBranchPath = extensionBranchPath + '.cloudStorage';
  2697. // https://github.com/gorhill/uBlock/issues/80#issuecomment-132081658
  2698. // We must use get/setComplexValue in order to properly handle strings
  2699. // with unicode characters.
  2700. var iss = Ci.nsISupportsString;
  2701. var argstr = Components.classes['@mozilla.org/supports-string;1']
  2702. .createInstance(iss);
  2703. var options = {
  2704. defaultDeviceName: '',
  2705. deviceName: ''
  2706. };
  2707. // User-supplied device name.
  2708. try {
  2709. options.deviceName = Services.prefs
  2710. .getBranch(extensionBranchPath + '.')
  2711. .getComplexValue('deviceName', iss)
  2712. .data;
  2713. } catch(ex) {
  2714. }
  2715. var getDefaultDeviceName = function() {
  2716. var name = '';
  2717. try {
  2718. name = Services.prefs
  2719. .getBranch('services.sync.client.')
  2720. .getComplexValue('name', iss)
  2721. .data;
  2722. } catch(ex) {
  2723. }
  2724. return name || window.navigator.platform || window.navigator.oscpu;
  2725. };
  2726. var start = function(dataKeys) {
  2727. var extensionBranch = Services.prefs.getBranch(extensionBranchPath + '.');
  2728. var syncBranch = Services.prefs.getBranch('services.sync.prefs.sync.');
  2729. // Mark config entries as syncable
  2730. argstr.data = '';
  2731. var dataKey;
  2732. for ( var i = 0; i < dataKeys.length; i++ ) {
  2733. dataKey = dataKeys[i];
  2734. if ( extensionBranch.prefHasUserValue('cloudStorage.' + dataKey) === false ) {
  2735. extensionBranch.setComplexValue('cloudStorage.' + dataKey, iss, argstr);
  2736. }
  2737. syncBranch.setBoolPref(cloudBranchPath + '.' + dataKey, true);
  2738. }
  2739. };
  2740. var push = function(datakey, data, callback) {
  2741. var branch = Services.prefs.getBranch(cloudBranchPath + '.');
  2742. var bin = {
  2743. 'source': options.deviceName || getDefaultDeviceName(),
  2744. 'tstamp': Date.now(),
  2745. 'data': data,
  2746. 'size': 0
  2747. };
  2748. bin.size = JSON.stringify(bin).length;
  2749. argstr.data = JSON.stringify(bin);
  2750. branch.setComplexValue(datakey, iss, argstr);
  2751. if ( typeof callback === 'function' ) {
  2752. callback();
  2753. }
  2754. };
  2755. var pull = function(datakey, callback) {
  2756. var result = null;
  2757. var branch = Services.prefs.getBranch(cloudBranchPath + '.');
  2758. try {
  2759. var json = branch.getComplexValue(datakey, iss).data;
  2760. if ( typeof json === 'string' ) {
  2761. result = JSON.parse(json);
  2762. }
  2763. } catch(ex) {
  2764. }
  2765. callback(result);
  2766. };
  2767. var getOptions = function(callback) {
  2768. if ( typeof callback !== 'function' ) {
  2769. return;
  2770. }
  2771. options.defaultDeviceName = getDefaultDeviceName();
  2772. callback(options);
  2773. };
  2774. var setOptions = function(details, callback) {
  2775. if ( typeof details !== 'object' || details === null ) {
  2776. return;
  2777. }
  2778. var branch = Services.prefs.getBranch(extensionBranchPath + '.');
  2779. if ( typeof details.deviceName === 'string' ) {
  2780. argstr.data = details.deviceName;
  2781. branch.setComplexValue('deviceName', iss, argstr);
  2782. options.deviceName = details.deviceName;
  2783. }
  2784. getOptions(callback);
  2785. };
  2786. return {
  2787. start: start,
  2788. push: push,
  2789. pull: pull,
  2790. getOptions: getOptions,
  2791. setOptions: setOptions
  2792. };
  2793. })();
  2794. /******************************************************************************/
  2795. /******************************************************************************/
  2796. vAPI.browserData = {};
  2797. /******************************************************************************/
  2798. // https://developer.mozilla.org/en-US/docs/HTTP_Cache
  2799. vAPI.browserData.clearCache = function(callback) {
  2800. // PURGE_DISK_DATA_ONLY:1
  2801. // PURGE_DISK_ALL:2
  2802. // PURGE_EVERYTHING:3
  2803. // However I verified that no argument does clear the cache data.
  2804. // There is no cache2 for older versions of Firefox.
  2805. if ( Services.cache2 ) {
  2806. Services.cache2.clear();
  2807. } else if ( Services.cache ) {
  2808. Services.cache.evictEntries(Services.cache.STORE_ON_DISK);
  2809. }
  2810. if ( typeof callback === 'function' ) {
  2811. callback();
  2812. }
  2813. };
  2814. /******************************************************************************/
  2815. vAPI.browserData.clearOrigin = function(/* domain */) {
  2816. // TODO
  2817. };
  2818. /******************************************************************************/
  2819. /******************************************************************************/
  2820. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager2
  2821. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  2822. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  2823. vAPI.cookies = {};
  2824. /******************************************************************************/
  2825. vAPI.cookies.CookieEntry = function(ffCookie) {
  2826. this.domain = ffCookie.host;
  2827. this.name = ffCookie.name;
  2828. this.path = ffCookie.path;
  2829. this.secure = ffCookie.isSecure === true;
  2830. this.session = ffCookie.expires === 0;
  2831. this.value = ffCookie.value;
  2832. };
  2833. /******************************************************************************/
  2834. vAPI.cookies.start = function() {
  2835. Services.obs.addObserver(this, 'cookie-changed', false);
  2836. Services.obs.addObserver(this, 'private-cookie-changed', false);
  2837. cleanupTasks.push(this.stop.bind(this));
  2838. };
  2839. /******************************************************************************/
  2840. vAPI.cookies.stop = function() {
  2841. Services.obs.removeObserver(this, 'cookie-changed');
  2842. Services.obs.removeObserver(this, 'private-cookie-changed');
  2843. };
  2844. /******************************************************************************/
  2845. vAPI.cookies.observe = function(subject, topic, reason) {
  2846. //if ( topic !== 'cookie-changed' && topic !== 'private-cookie-changed' ) {
  2847. // return;
  2848. //}
  2849. //
  2850. if ( reason === 'cleared' && typeof this.onAllRemoved === 'function' ) {
  2851. this.onAllRemoved();
  2852. return;
  2853. }
  2854. if ( subject === null ) {
  2855. return;
  2856. }
  2857. if ( subject instanceof Ci.nsICookie2 === false ) {
  2858. try {
  2859. subject = subject.QueryInterface(Ci.nsICookie2);
  2860. } catch (ex) {
  2861. return;
  2862. }
  2863. }
  2864. if ( reason === 'deleted' ) {
  2865. if ( typeof this.onRemoved === 'function' ) {
  2866. this.onRemoved(new this.CookieEntry(subject));
  2867. }
  2868. return;
  2869. }
  2870. if ( typeof this.onChanged === 'function' ) {
  2871. this.onChanged(new this.CookieEntry(subject));
  2872. }
  2873. };
  2874. /******************************************************************************/
  2875. // Meant and expected to be asynchronous.
  2876. vAPI.cookies.getAll = function(callback) {
  2877. if ( typeof callback !== 'function' ) {
  2878. return;
  2879. }
  2880. var onAsync = function() {
  2881. var out = [];
  2882. var enumerator = Services.cookies.enumerator;
  2883. var ffcookie;
  2884. while ( enumerator.hasMoreElements() ) {
  2885. ffcookie = enumerator.getNext();
  2886. if ( ffcookie instanceof Ci.nsICookie ) {
  2887. out.push(new this.CookieEntry(ffcookie));
  2888. }
  2889. }
  2890. callback(out);
  2891. };
  2892. vAPI.setTimeout(onAsync.bind(this), 0);
  2893. };
  2894. /******************************************************************************/
  2895. vAPI.cookies.remove = function(details, callback) {
  2896. var uri = Services.io.newURI(details.url, null, null);
  2897. var cookies = Services.cookies;
  2898. cookies.remove(uri.asciiHost, details.name, uri.path, false, {});
  2899. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false, {});
  2900. if ( typeof callback === 'function' ) {
  2901. callback({
  2902. domain: uri.asciiHost,
  2903. name: details.name,
  2904. path: uri.path
  2905. });
  2906. }
  2907. };
  2908. /******************************************************************************/
  2909. /******************************************************************************/
  2910. })();
  2911. /******************************************************************************/