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.

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