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.

3359 lines
105 KiB

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