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.

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