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.

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